Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement datcontext per request/thread using factory pattern

Using this sample project as a guideline, I am setting up a new project. My project will follow the same basic architecture, only in addition to an mvc project, I will also have a wcf web service project(or possibly servicestack.net)

Instead of using Unity for DI as in the sample, I am using Ninject. Currently I am configuring Ninject as follows to only instantiate one instance of Database factory per web request(and thus one datacontext class per request (using EF 4.1 code first btw))

 kernel.Bind<IDatabaseFactory>()
       .To<DatabaseFactory>()
       .InScope(ctx => HttpContext.Current);

I am curious if this method is sufficient? Or would it be better to let the factory class handle the instantiation of datacontext per http request(and possibly per thread if I were design for non web based front-ends in the future)? If so, are there any examples out there of how to go about this?

Or is there a completely better solution to handle this?

like image 402
stephen776 Avatar asked Oct 10 '22 21:10

stephen776


1 Answers

You should use .InRequestScope() instead of .InScope(ctx => HttpContext.Current). It ensures that the appropriate scope is used depending on whether the instance is requested via WCF or via ASP.NET MVC. Unfortunately to take full advantage of this you'll have to use the current continous integration builds from http://teamcity.codebetter.com . See also

https://github.com/ninject/ninject.extensions.wcf

https://github.com/ninject/ninject.web.mvc

like image 195
Remo Gloor Avatar answered Oct 13 '22 10:10

Remo Gloor