How to properly use Dispose in Unit Of Work Pattern? - entity-framework

I know this question has been asked several times before, but I couldn't get the answer I was looking for.
So, I've implemented the Repository (generic) and UOW pattern, so I can access my DB using EF. Here's part of the UnitOfWork class:
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
The question is: Who is calling the void Dispose method?? I've seen no example of the usage of that method.
this it the upper part of the Unit Of Work class:
private BDEntities entities = null;
public UnitOfWork()
{
if (entities == null)
{
entities = new BDEntities();
}
}
Is this right? should I use "Using"? and if yes, than why do I need the Dispose method?
Can you give me an example of a proper and simple usage?
Thank you,
Rotem

The reason why you have not come across any examples about who calls the dispose is because UoW is usually used together with dependency injection and a dependency injection container, like Autofac. And in this case, it is the responsibility of this container to create objects and dispose of them later. Granted, this is not the only way UoW can be used, but it is a common pattern.
As for answering your question: I think the approach that you are taking is more or less right. The UoW class should be the one that wraps the context, so it should be the one to dispose it as well (essentially, the DbContext itself is a UoW).
You can simplify the Dispose method though. Since you do not have any unmanaged and not IDisposable resources (like pointers), it is completely enough to call the Dispose method of the context in the Dispose method of the UoW:
public void Dispose()
{
entities.Dispose();
}
(No other Dispose method, no SuppressFinalize calls).
And yes, you should absolutely use using. And that's exactly why you need a the Dispose() method; only objects that are of a type that implements IDisposable can be used in a using block. If you write a using block, it basically translates to a try-finally block; your code from inside the using block goes into the try block, and in the finally, the Dispose() is called.

Related

Can I keep Entity Framework context as class variable?

I'm used to working the database connections where you connect/open/close as fast as possible in each method. I'm now working with the Entity Framework and so my methods all do this type of thing:
using (var context = new FooEntities()) {
// linq to sql query here
}
I've been told that with Entity Framework I can actually have that context variable be a class level variable and not have to instantiate it in each method. Is that really the case, or should I continue this pattern in each method?
I'm using version 5.0.0 of the framework if that makes a difference.
It depends on how you are expecting it to act. The only reason you'd want it to stick around is if you wanted to use the caching feature of DbContext across multiple method calls. But since its pulling connections from the Pool anyway, disposing of a DbContext shouldn't really impact performance when creating a new one.
For me personally, I create the context as close as possible and kill it as soon as possible. Thus, the Get calls should use AsNoTracking() to speed up the calls a lot if you don't care about trying to update them later. You could also create a DbContextFactory so each class could control that interaction as it sees fit. (i.e. Method A always creates a new one, but Methods B and C could share if either one called first). Though, that could cause its own issues down the road, but then you can opt into those conditions.
You can have Context as a property of a class, but you have to consider how to control the disposing of the Context. For example:
public class UnitOfWork:IDisposable
{
public DbContext Context { get; set; }
public UnitOfWork()
{
Context = null; //initialize context here
}
public void DoWorkWithContext1()
{
//anything you need
}
public void DoWorkWithContext2()
{
//anything you need
}
public void Dispose()
{
if (Context != null)
Context.Dispose();
}
}
Then you'll use the class in this way:
using (var unit= new UnitOfWork())
{
unit.DoWorkWithContext1();
unit.DoWorkWithContext2();
}

Nested DbContext due to method calls - Entity Framework

In the following case where two DbContexts are nested due to method calls:
public void Method_A() {
using (var db = new SomeDbContext()) {
//...do some work here
Method_B();
//...do some more work here
}
}
public void Method_B() {
using (var db = new SomeDbContext()) {
//...do some work
}
}
Question:
Will this nesting cause any issues? (and will the correct DbContext be disposed at the correct time?)
Is this nesting considered bad practice, should Method_A be refactored into:
public void Method_A() {
using (var db = new SomeDbContext()) {
//...do some work here
}
Method_B();
using (var db = new SomeDbContext()) {
//...do some more work here
}
}
Thanks.
Your DbContext derived class is actually managing at least three things for you here:
the metadata that describes your database and your entity model,
the underlying database connection, and
a client side "cache" of entities loaded using the context, for change tracking, relationship fixup, etc. (Note that although I term this a "cache" for want of a better word, this is generally short lived and is just to support EFs functionality. It's not a substitute for proper caching in your application if applicable.)
Entity Framework generally caches the metadata (item 1) so that it is shared by all context instances (or, at least, all instances that use the same connection string). So here that gives you no cause for concern.
As mentioned in other comments, your code results in using two database connections. This may or may not be a problem for you.
You also end up with two client caches (item 3). If you happen to load an entity from the outer context, then again from the inner context, you will have two copies of it in memory. This would definitely be confusing, and could lead to subtle bugs. This means that, if you don't want to use shared context objects, then your option 2 would probably be better than option 1.
If you are using transactions, there are further considerations. Having multiple database connections is likely to result in transactions being promoted to distributed transactions, which is probably not what you want. Since you didn't make any mention of db transactions, I won't go into this further here.
So, where does this leave you?
If you are using this pattern simply to avoid passing DbContext objects around in your code, then you would probably be better off refactoring MethodB to receive the context as a parameter. The question of how long-lived context objects should be comes up repeatedly. As a rule of thumb, create a new context for a single database operation or for a series of related database operations. (See, for example this blog post and this question.)
(As an alternative, you could add a constructor to your DbContext derived class that receives an existing connection. Then you could share the same connection between multiple contexts.)
One useful pattern is to write your own class that creates a context object and stores it as a private field or property. Then you make your class implement IDisposable and its Dispose() method disposes the context object. Your calling code news up an instance of your class, and doesn't have to worry about contexts or connections at all.
When might you need to have multiple contexts active at the same time?
This can be useful when you need to write code that is multi-threaded. A database connection is not thread-safe, so you must only ever access a connection (and therefore an EF context) from one thread at a time. If that is too restrictive, you need multiple connections (and contexts), one per thread. You might find this interesting.
You can alter your code by passing to Method_B the context. If you do so, the creation of the second db call SomeDbContext will not be necessary.
there a question an answer in stackoverflow in this link
Proper use of "Using" statement for datacontext
It is a bit late answer, but still people may be looking so here is another way.
Create class, that cares about disposing for you. In some scenarios, there would be a function usable from different places in solution. This way you avoid creating multiple instances of DbContext and you can use nested calls as many as you like.
Pasting simple example.
public class SomeContext : SomeDbContext
{
protected int UsingCount = 0;
public static SomeContext GetContext(SomeContext context)
{
if (context != null)
{
context.UsingCount++;
}
else
{
context = new SomeContext();
}
return context;
}
private SomeContext()
{
}
protected bool MyDisposing = true;
protected override void Dispose(bool disposing)
{
if (UsingCount == 0)
{
base.Dispose(MyDisposing);
MyDisposing = false;
}
else
{
UsingCount--;
}
}
public override int SaveChanges()
{
if (UsingCount == 0)
{
return base.SaveChanges();
}
else
{
return 0;
}
}
}
Example of usage
public class ExmapleNesting
{
public void MethodA()
{
using (var context = SomeContext.GetContext(null))
{
// manipulate, save it, just do not call Dispose on context in using
MethodB(context);
}
MethodB();
}
public void MethodB(SomeContext someContext = null)
{
using (var context = SomeContext.GetContext(someContext))
{
// manipulate, save it, just do not call Dispose on context in using
// Even more nested functions if you'd like
}
}
}
Simple and easy to use.
If you think number of connections to Database,and impact of times that new connections must be opened, not an important problem and you have no limitation for support your application to run at best performance, everything is OK.
Your code works well. Because create just a db context has a low impact in your performance,meta data will be cached after first loading, and connection to your database just occurs when the code need to execute a query. With liitle performance consideration and code design, I offer you to make context factory to have just an instance of each Db Context for each instance of your application.
You can take a look at this link for more performance considerations
http://msdn.microsoft.com/en-us/data/hh949853

What is the best usage of Dispose for "Entity Framework"?

What is the true usage of dispose ?
This is first (my) approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public RequestService() //Constructor
{
db = new requestDBEntities ();
}
public List<RequestStatus> ddlFill()
{
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
db.Dispose(); //<--Dispose requestDBEntities();
GC.SuppressFinalize(this);
}
And second approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public List<RequestStatus> ddlFill()
{
using (db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
GC.SuppressFinalize(this);
}
Page Code-behind:
using (RequestService _reqService = new RequestService ())
{
ddlRequestStatus.DataSource = _reqService.ddlFill();
ddlRequestStatus.DataBind();
//Some Insert,Update,Delete operations...
}
Thank you..
It's difficult (impossible) to say which is the better approach, since we don't know your exact design choice. From the perspective of a simple app, it may seem that the two examples are equivalent (more or less), but they really do behave in entirely different ways.
The fundamental question here is: Should the lifetime of db be comparable to the lifetime of its enclosing RequestService instance?
If yes, then the first code example is the way to do things. Resources will be managed as expected (db disposes its stuff at the same time the RequestService object is asked to dispose of its resources), and the lifetime of the two will be pretty much identical (db is constructed in the RequestService constructor, and db become collectable as soon as its RequestService object becomes collectable).
However, if the answer is "no", then the second example is (almost) the way to do things - since you generate a collection view of the RequestStatus object from db, you really have no reason to keep db around any longer. However, to make this a bit better, may I suggest restricting the scope of db to within the ddlFill method:
public List<RequestStatus> ddlFill()
{
using (var db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
No need for an extraneous class member when a stack value suffices.
What for in second example you have declared requestDBEntities db; at class level instead of having it as a stack variable?
Comparing your approaches, the question is - are you ready to create requestDBEntities on each call? If you are - second approach is better, in fact if there is nothing else you haven'y posted - you don't need dispose at all. But you'll have extra time penalty on instantiating/releasing requestDBEntities on each call.

Does the MEF Container.Dispose dispose added catalogs?

This is similar to how my code looks
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
_container = new CompositionContainer(catalog);
Code Analysis is showing a warning CA2000: call Dispose on catalog before all references to it are out of scope.
So I'm not sure if I need to suppress the warning or turn _catalog into a field + Dispose it.
The MEF Docs don't seem to mention this.
According to the MEF Preview 9 source code (which probably closely matches the code that shipped in .NET 4) CompositionContainer will wrap the catalog in a CatalogExportProvider. This export provider is stored in a field and disposed along with the container. However, CatalogExportProvider.Dispose will not in turn dispose the wrapped ComposablePartCatalog.
Therefore the answer is no: CompositionContainer does not dispose the catalog.
You can verify this by running this code, which will not print anything to the console:
class MyCatalog : ComposablePartCatalog
{
protected override void Dispose(bool disposing)
{
Console.WriteLine("Disposed!");
base.Dispose();
}
public override IQueryable<ComposablePartDefinition> Parts
{
get { throw new NotImplementedException(); }
}
}
class Program
{
static void Main(string[] args)
{
var container = new CompositionContainer(new MyCatalog());
container.Dispose();
Console.ReadKey();
}
}
As Wim already discovered neither the CompsitionContainer nor the CatalogExportProvider will call dispose on the catalog. Neither of them created the catalog thus neither of them own it and as such will not call Dispose on it. Whoever constructs the catalog should be the one that disposes it.
There are a lot of scenarios where someone would want to share a catalog instance with multiple containers which is why the container doesn't have ownership of the catlaog and therefore doesn't dispose it.

Strong reference of Autofac 2

newbie here, sorry if this is an obvious question.
I've read from this page: http://code.google.com/p/autofac/wiki/NewInV2
In Autofac 1, weak references are held by the container. This makes sense if the objects being referenced use disposal to release GC/finalizer resources, but if the dispose method contains application logic then GC timing could introduce unexpected behaviour.
Autofac 2 holds normal references. To opt out of this behaviour and mange disposal manually, use the ExternallyOwned registration modifier.
Is that mean when I need to release an object that is resolved by Autofac to the GC, I cannot simply say:
a = null;
because Autofac holds a strong reference to the object. Instead, I should use Owned<>:
public class MyClass
{
public MyClass(Owned<A> a)
{
a.Value.Dosomething();
a.Dispose();
}
}
or use the ExternallyOwned registration modifier:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).ExternallyOwned();
later on, I should be able to use a = null to release the object to the GC.
Is that right?
Thanks!
By default, you don't need to dispose anything - Autofac will automatically identify and dispose any IDisposable instances it created when their containing lifetime scope is disposed.
You only need to use Owned<T> or ExternallyOwned() if you have a reason to manage the lifetime of the object manually. If you resolve an Owned<T> then you should call t.Dispose() yourself - the common usage pattern is to take a dependency on a factory delegate:
public class MyClass
{
private Func<Owned<User>> myDisposableFactory;
public MyClass(Func<Owned<User>> myDisposableFactory)
{
this.myDisposableFactory = myDisposableFactory;
}
public void DoSomething()
{
using (var disposable = this.myDisposableFactory())
{
// ...
disposable.Dispose();
}
}
}
If you register a type as ExternallyOwned() then Autofac will not dispose of any resolved instance when the containing lifetime scope ends - it's up to you to manage it.
Take a look at Nicholas Blumhardt's article on lifetimes for more information.