I see in many examples about MVC, Repository pattern, Unit of Work and EF, for instance here, that both interfaces and classes implement the IDisposable
interface. I guess this interface exposes just the method Dispose()
with 2 overloads.
However in many other examples made by senior programmers, I do not see such implementation. Actually to me it seems quite logic that one a component is dismissed on every web request, since every request gets a brand new controller instance.
Or even if this is not the case, I guess by using a dependency injection framework such as Ninject, we delegate all this disposal tasks to the very framework.
It can also be the case that the implementation of IDisposable was required in older version of the EF or MVC framework.
Anybody might point me to the right direction?
UPDATE
The automatic disposal of the context can be seen in a layered application with Service and Repository layer. Assume that from both components we return IQueryable<T>
objects, if we try to populate the objects from the controller, by iterating its items or call the ToList()
method, we get a runtime error saying that the context is unreachable (closed)
The common pattern is to have an instance of the Repository in every Controller and to link the Disposal into the Dispose() of the Controller.
So I would say the pattern is generally required.
However in many other examples made by senior programmers, I do not see such implementation.
There are a few possibilities:
Point to a concrete example and we can find out.
Usually in most of the examples you can find on interner about Repository
pattern using EF the Context has a Dispose
method.
Now you don't strictly need to call the Dispose method on the Context
but it may be a good practice for the reason below:
DataContext holds state (for example, a SqlConnection and pointers to the objects you have retrieved). These will eventually get cleaned up by the GC once you release all references, but some of these objects (for example, the underlying SqlConnection) may be holding resources that you typically want to release as soon as your are finished, rather than relying on the GC to clean up.
For lazy people: you can even wrap the context within a using statement which will call the dispose for you when the object get out from the scope of the using itself
more info at :
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe/
here you can also find an example that regarding Repository patter in EF
http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With