Entity Framework, UnitofWork pattern with dispose method - c#

A sample of uow:
using System;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
public class UnitOfWork : IDisposable
{
private SchoolContext context = new SchoolContext();
private GenericRepository<Department> departmentRepository;
private GenericRepository<Course> courseRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
public GenericRepository<Course> CourseRepository
{
get
{
if (this.courseRepository == null)
{
this.courseRepository = new GenericRepository<Course>(context);
}
return courseRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
As you see uow includes dispose method and inside it disposes dbContex object. Why should we explicitly dispose the dbContext object. Since it is a member of uow, outside the scope it will disposed by garbace collector automaticly. So, why are we doing this manually? As an example:
using(Uow uowObject = new Uow())
{
//there is a dbcontext
}
//it will be disposed automaticly by gc

Outside the scope the variable is no longer reachable but that doesn't mean disposed. As a rule of thumb, every class that implements IDisposable should be disposed. In the case of EF, it will clear the cache, the graph that tracks object changes and rollback any uncommitted transactions as well.

With GC, you don't know when GC will be started. Even the variable is out of scope, it doesn't mean it has been garbage collected. With dispose pattern, you can free the memory right away.
From MSDN :In determining when to schedule garbage collection, the runtime takes into account how much managed memory is allocated. If a small managed object allocates a large amount of unmanaged memory, the runtime takes into account only the managed memory, and thus underestimates the urgency of scheduling garbage collection.
So for the managed objects which hold native resource, you should call dispose to free the native resource.

Related

Using IDisposable in expression-bodied member [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?
I have a Class which has some unmanaged resources. My class implements the IDisposable interface and releases the unmanaged resources in the Dispose() method. Do I have to call the Dispose() method or will it be automatically called somehow? Will the Garbage Collector call it?
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
The preferable way for a client is to use the using statement which handles automatic calling of Dispose() even if there are exceptions.
A proper implementation of IDisposable is:
class MyClass : IDisposable
{
private bool disposed = false;
void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Manual release of managed resources.
}
// Release unmanaged resources.
disposed = true;
}
}
~MyClass() { Dispose(false); }
}
If the user of the class calls Dispose() the cleanup takes place directly. If the object is catched by the garbage collector, it calls Dispose(false) to do the cleanup. Please note that when called from the finalizer (the ~MyClass method) managed references may be invalid, so only unmanaged resources can be released.
If you instantiate your object in a using statement, Dispose() is called for you when code exits the using block
using(var myObject = new MyDisposableObject())
{
blah();
} // Dispose() is called here (or whenever the code exits the block)
If you don't use using, then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().
Also, you (the implementor of MyObject) can add support for a finalizer in case your caller doesn't call Dispose(). More info here.
You will have to call this method manually, maybe (assuming that "MyClass" implements "IDisposable") in a construct like
using(var myclass = new MyClass())
{
// do something with myclass
}
// now 'myclass'is Disposed
In C# 8.0, you can write as below statement:
using var myclass=new MyClass();
and the "myclass" will be disposed automatically at the end of the scope.
The advantage of the using statement (compared to calling Dispose() explicitly) is that Dispose() is called no matter how you exit this block: by running past the end, encountering a return statement or having an exception thrown.
To make sure the resources are correctly disposed, you need to both implement IDisposable and call Dispose in the destructor(finalizer).
class Foo : IDisposable
{
private bool m_disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Foo()
{
Dispose(false);
}
protected void Dispose(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
//release managed resources
}
//release unmanaged resources
m_disposed = true;
}
}
}

Implementing IDisposable correctly

In my classes I implement IDisposable as follows:
public class User : IDisposable
{
public int id { get; protected set; }
public string name { get; protected set; }
public string pass { get; protected set; }
public User(int UserID)
{
id = UserID;
}
public User(string Username, string Password)
{
name = Username;
pass = Password;
}
// Other functions go here...
public void Dispose()
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
}
In VS2012, my Code Analysis says to implement IDisposable correctly, but I'm not sure what I've done wrong here.
The exact text is as follows:
CA1063 Implement IDisposable correctly Provide an overridable implementation of Dispose(bool) on 'User' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources. stman User.cs 10
For reference: CA1063: Implement IDisposable correctly
I've read through this page, but I'm afraid I don't really understand what needs to be done here.
If anyone can explain in more layman's terms what the problem is and/or how IDisposable should be implemented, that will really help!
This would be the correct implementation, although I don't see anything you need to dispose in the code you posted. You only need to implement IDisposable when:
You have unmanaged resources
You're holding on to references of things that are themselves disposable.
Nothing in the code you posted needs to be disposed.
public class User : IDisposable
{
public int id { get; protected set; }
public string name { get; protected set; }
public string pass { get; protected set; }
public User(int userID)
{
id = userID;
}
public User(string Username, string Password)
{
name = Username;
pass = Password;
}
// Other functions go here...
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
}
// free native resources if there are any.
}
}
First of all, you don't need to "clean up" strings and ints - they will be taken care of automatically by the garbage collector. The only thing that needs to be cleaned up in Dispose are unmanaged resources or managed recources that implement IDisposable.
However, assuming this is just a learning exercise, the recommended way to implement IDisposable is to add a "safety catch" to ensure that any resources aren't disposed of twice:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
// Indicate that the instance has been disposed.
_disposed = true;
}
}
The following example shows the general best practice to implement IDisposable interface. Reference
Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory longer that it should (Note: Read how Finalization works). Below example elaborate all above.
public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
public static void Main()
{
// Insert code here to create
// and use the MyResource object.
}
}
IDisposable exists to provide a means for you to clean up unmanaged resources that won't be cleaned up automatically by the Garbage Collector.
All of the resources that you are "cleaning up" are managed resources, and as such your Dispose method is accomplishing nothing. Your class shouldn't implement IDisposable at all. The Garbage Collector will take care of all of those fields just fine on its own.
You need to use the Disposable Pattern like this:
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose any managed objects
// ...
}
// Now disposed of any unmanaged objects
// ...
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Destructor
~YourClassName()
{
Dispose(false);
}
You have no need to do your User class being IDisposable since the class doesn't acquire any non-managed resources (file, database connection, etc.). Usually, we mark classes as
IDisposable if they have at least one IDisposable field or/and property.
When implementing IDisposable, better put it according Microsoft typical scheme:
public class User: IDisposable {
...
protected virtual void Dispose(Boolean disposing) {
if (disposing) {
// There's no need to set zero empty values to fields
// id = 0;
// name = String.Empty;
// pass = String.Empty;
//TODO: free your true resources here (usually IDisposable fields)
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
Idisposable is implement whenever you want a deterministic (confirmed) garbage collection.
class Users : IDisposable
{
~Users()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
// This method will remove current object from garbage collector's queue
// and stop calling finilize method twice
}
public void Dispose(bool disposer)
{
if (disposer)
{
// dispose the managed objects
}
// dispose the unmanaged objects
}
}
When creating and using the Users class use "using" block to avoid explicitly calling dispose method:
using (Users _user = new Users())
{
// do user related work
}
end of the using block created Users object will be disposed by implicit invoke of dispose method.
I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:
https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About
The only other thing that would likely be helpful is suppressing that code analysis warning... https://learn.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017

c# Dispose pattern

Here is a typical IDispose implementation. What I don't understand is the destructor?
If the user of your class forgets to call Dispose, wouldn't you have a resource leak since the destructor will not call r1.Dispose()?
public class DisposableObject : IDisposable
{
private bool disposed;
private UnmanagedResource r1;
public DisposableObject()
{
r1 = new UnmanagedResource();
}
~DisposableObject()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// clean up managed resources
//call dispose on your member objects
r1.Dispose();
}
// clean up unmanaged resources
this.disposed = true;
}
}
public void SomeMethod()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
No - the GC will call the destructor once all references to the object are gone (this is not deterministic, however).
If r1 is truly a native resource (which it doesn't look like it in your example), it should not be disposed of inside the if(disposing) block but after it. Pay particular attention to:
if (disposing)
{
// free managed resources
if (managedResource != null)
{
managedResource.Dispose();
managedResource = null;
}
}
// free native resources if there are any.
if (nativeResource != IntPtr.Zero)
{
Marshal.FreeHGlobal(nativeResource);
nativeResource = IntPtr.Zero;
}
From Implement IDisposable Correctly - MSDN
If r1 is a managed resource with its own implementation of IDisposable, assuming it is implemented properly, any native resources will be cleaned up properly in its finalizer (which is why you don't need to worry about it in your own).
The reason for the destructor (finalizer) to call Dispose is because Garbage Collector calls it before it collects an object, guaranteeing that at least at some point the UnmanagedResource will be freed.
By using using and try...finally you can enforce the resource to be disposed as soon as they are not needed
http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx
If you really want to, you can add a finalizer:
~DisposeImplementation()
{
Dispose(false);
}
But it should only be used as a true last resort, not something to rely on directly.
In .Net, we have a feature called Garbage Collection. Garbage Collection finalizes all Objects that are not referenced (any more). Your Destructor / finalizer then calls Dispose().
If your user forgets to remove those references, you will end up with sort-of a leak.
But that's what using is for : avoid memory blockage by defining your disposables only in the scope of requirement.
The pattern exists because the garbage collector does not guarantee the order that managed objects will be garbage collected. So in the finalizer you are not guaranteed that the r1 reference is still valid.
Your r1 reference has a class name of UnmanagedResource but it is clearly a managaged type. For a real unmanned resource you would only have an IntPtr or some other token. To ensure that r1 does non like it's resource it should implement the same Dispose pattern and free it's unmanaged resource outside of the if (disposing) check.

How to manage disposing an IList object when subsets of the list exist?

It's hard to describe this problem with words, so here's code:
public class Item : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
_disposed = true;
if (disposing)
{
//dispose managed resources
if (_group != null) _group.Dispose();
_stream.Close(); //or some legitimate thing that needs cleaned up
}
//dispose unmanaged resources
}
ItemList _group;
public ItemList Group { get{return _group;} set{_group = value;}}
public int SomeValue {get; set;}
}
public class ItemList : IList<Item>, IDisposable
{
public ItemList(IList<Item> list) : base(list)
{
list.ForEach(i => i.Group = this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
_disposed = true;
if (disposing)
{
//dispose managed resources
this.ForEach(i => i.Dispose());
}
//dispose unmanaged resources
}
public ItemList CreateSubSet(int value)
{
return new ItemList(this.Where(i => i.SomeValue == value));
}
}
So, if you start with an ItemList, and call ItemList.CreateSubSet(2), you'll be given a 2nd instance of ItemList that contains some of the same Item instances from the original ItemList. So how do you ever go about calling Dispose() on either instance of ItemList, because once you do that, you'll actually dispose both of them?
I've considered making Item not be responsible for disposing _group, but even then if you call Dispose() on one of the instances of ItemList, you end up disposing SOME of the Item objects that make up the other ItemList.
Do you have to do some sort of reference counting within Item, and only dispose it when there's only 1 reference left? In conjunction with this, perhaps empty the ItemList object before calling Dispose() if you know it is a subset? Or maybe make a ItemSubsetList class which is identical to ItemList but is not disposable? What if the ItemSubsetList escapes the scope of the ItemList, then how would you clean it up?
Any design pattern or guidance?
Are the objects mutable or immutable, and what is the cost associated with them?
In general, I would suggest that mutable objects should almost always have one clearly-recognizable owner at any given time, whether or not they hold any resources. It's perfectly acceptable for many references to exist to a mutable object, but there should be a clear distinction between an entity which holds a reference to an IList<T> which it owns, and one which holds a reference to an IList<T> which is owned by someone else (the latter entity might e.g. have been given the reference so that it can copy some data into it for the owner's benefit).
The only times I would expect that ownership of IDisposable objects would be problematical in a scenario such as yours would be if the objects themselves are immutable except for being disposable (meaning the only way their state can change is when they are disposed). If that situation applies, I would consider your situation is one of the very few in which abandoning items without disposal might be reasonable, if you can ensure that (1) you know what the costs are, and they are acceptable, and (2) you use a dictionary of WeakReference or some similar structure to recycle instances that have not yet been recognized as eligible for finalization. Such an approach is hardly pretty, but may in some cases be the best.

Is IDisposable.Dispose() called automatically? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?
I have a Class which has some unmanaged resources. My class implements the IDisposable interface and releases the unmanaged resources in the Dispose() method. Do I have to call the Dispose() method or will it be automatically called somehow? Will the Garbage Collector call it?
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
The preferable way for a client is to use the using statement which handles automatic calling of Dispose() even if there are exceptions.
A proper implementation of IDisposable is:
class MyClass : IDisposable
{
private bool disposed = false;
void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Manual release of managed resources.
}
// Release unmanaged resources.
disposed = true;
}
}
~MyClass() { Dispose(false); }
}
If the user of the class calls Dispose() the cleanup takes place directly. If the object is catched by the garbage collector, it calls Dispose(false) to do the cleanup. Please note that when called from the finalizer (the ~MyClass method) managed references may be invalid, so only unmanaged resources can be released.
If you instantiate your object in a using statement, Dispose() is called for you when code exits the using block
using(var myObject = new MyDisposableObject())
{
blah();
} // Dispose() is called here (or whenever the code exits the block)
If you don't use using, then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().
Also, you (the implementor of MyObject) can add support for a finalizer in case your caller doesn't call Dispose(). More info here.
You will have to call this method manually, maybe (assuming that "MyClass" implements "IDisposable") in a construct like
using(var myclass = new MyClass())
{
// do something with myclass
}
// now 'myclass'is Disposed
In C# 8.0, you can write as below statement:
using var myclass=new MyClass();
and the "myclass" will be disposed automatically at the end of the scope.
The advantage of the using statement (compared to calling Dispose() explicitly) is that Dispose() is called no matter how you exit this block: by running past the end, encountering a return statement or having an exception thrown.
To make sure the resources are correctly disposed, you need to both implement IDisposable and call Dispose in the destructor(finalizer).
class Foo : IDisposable
{
private bool m_disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Foo()
{
Dispose(false);
}
protected void Dispose(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
//release managed resources
}
//release unmanaged resources
m_disposed = true;
}
}
}

Categories