Adding a Dispose Method to Model Repositories

Posted Saturday, January 14, 2012 in Old JamesCMS Posts

Here's an example of adding the IDisposable interface to a class. Specifically this is modeled after the repository classes such as those seen in the MVC Nerd Dinner project. In the case where you don't need or want to use direct injection to add your data repositories to a controller you can implement the dispose method. This will allow you to use a using statement with your repository.

{{C#}}
public void Dispose()
{
	this.Dispose(true);
	GC.SuppressFinalize(this);
}
 
~RepositoryName()
{
	Dispose(false);
}
 
protected virtual void Dispose(bool disposing)
{
	if (disposing)
	{
		if (datacontext != null)
		{
			datacontext.Dispose();
			datacontext = null;
		}
	}
}