ASP.NET MVC3 – Unit of Work Principle Causing Problems

asp.net-mvc-3entity-frameworkmultithreadingunit-of-work

I am implementing a website using MVC3, Entity Framework 4.1 and Repositoty pattern, Unit of work principle. But I am facing a big problem while implementing this.

I have developed a static ObjectContext class. This class is used across all the repositories so unit of work pattern is followed. I have e.g. ICustomer, IProduct repositories. I use specifically only one repository in a controller and that too is injected using NInject.

CustomerController(ICustomer customer)
{
}

ProductController(IProduct product)
{
}

Since object context class is static and IProduct, ICustomer have parameterised constructor which accepts the objectContext class, these two will share the same ObjectContext instance.

When the execution is single threaded everything goes fine, but in multi-threading I get an unhandled exception, because of one repository closing the connection which was being used by other. I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Can you please suggest a solution for this?

Best Answer

static ObjectContext class

This is actually even worse than what you think. The ObjectContext class is not thread safe so even if you manage to get what you think is good synchronization, (without actually locking) you will still be throwing exceptions all the time in a multi-user environment.

The ADO.NET team recommends using a new ObjectContext every time you plan on querying the database. How else could anyone separate their data access classes from each other if this weren't the case?

I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Not true at all. The unit of work pattern has nothing to do with having a single repository for an entire application--otherwise, every entity framework tutorial would start you off by showing you how to create your static ObjectContext.

It simply means that if you can't commit the unit of work, the entire commit will be backed out and the entire commit must succeed for it to be successful; it's a single logical transaction.

If you need to keep objects around for the life of the application, look into caching them in a data structure other than an ObjectContext.