How to properly dispose the ObjectContext in a Repository and Unit of Work pattern
I'm using Entity Framework 4 and I have created a UnitOfWork class that creates my Context and exposes that through a public property as a IContext interface. The Context class inherits from ObjectContext and exposes my Poco entities as public properties e.g.
public IObjectSet<User> Users
{
get { return _users ?? (_users = CreateObjectSet<User>("Users")); }
}
private IObjectSet<User> _users;
I have also created a few repository clas开发者_如何学Cses that takes that context as a constructor parameter and uses that context when executing queries in the repository classes. This is how I use the whole thing together:
using(var uow = new UnitOfWork(connectionstring))
{
using(var repository = new UserRepository(uio.Context))
{
//This is the place where a connection is opened in the database
var user = repository.GetUserByName(username);
}
}
//The connection is still open here even though
The UnitOfWork class implementes the IDisposable interface and calls Context.Dispose() inside it's Dispose method.
When I close my application the open connection in my database is gone, so my question is: What is going on here? :-) How should I properly dispose the Context (ObjectContext) instance in my UnitOfWork class in order to close the opened connection in my database?
I think you are doing things properly with regard to disposing the Context. The Sql Server Provider supports connection pooling, so what you're seeing after the end of the using(var uow = new UnitOfWork(connectionstring))
block is the connection in the pool.
For more information on connection pooling, see this article: http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
精彩评论