A day with .Net

My day to day experince in .net

Archive for November, 2014

One DbContext per request in an Asp.net MVC project by dependency injection and Ninject.

Posted by vivekcek on November 14, 2014

You know the entity framework dbcontext is not thread safe.

One of my friend faced an issue regarding the data mismatch happening in his MVC app.
After some inspection i learned that he was using a singleton dbcontext for his application.

Uhhhhhh! buddy static dbcontext and singleton dbcontext will screw you, why?

The Entity Framework data context object caches all of its data for as long as it exists. This means that it gets its data once from the database, then every time you request that data it returns it from its own cache. To function properly EF data contexts need to be created and destroyed with each page request.
Ok, So how we can achieve this. The Unit Of Work pattern with dependency inject can solve this well.
But he was not using Unit Of Work, aaah!!shit!! What to do??

Here comes the Ninject’s InRequestScope(), Which can spawn a new dbcontext instance per Http request, great!! i wana try.

If you don’t know how to use Ninject refer net.

1. Create an MVC app.

2. From Nugget use Ninject for MVC (Ninject.MVC3, Ninject.MVC4, Ninject.MVC5 etc..)

3. Let EmployeeDbContect be your dbcontect class.

4. Prepare your controller for dependency injection.

 public class HomeController : Controller
 {
 private EmployeeDbContext _context;

 public HomeController(EmployeeDbContext context)
 {
 _context = context;
 }

 public ActionResult Index()
 {
 return View();
 }

 }

5. Now in App_Start folder open NinjectWebCommon.cs. In CreateKernel method write these statements.

DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
kernel.Bind<EmployeeDbContext>().ToSelf().InRequestScope();
Advertisements

Posted in MVC | Tagged: , , , | Leave a Comment »