0

In MVC 4 I ended up overriding the controller factory to allow my ApplicationDbContext to be injected into each controller as it was instantiated. I was sure that throughout my requests I would never have two references to my ApplicationDbContext which ensured I didn't have any multithreading issues.

Now that MVC 5 is here, what's the proper way of implementing the repository pattern with OWIN? I've heard with OWIN that it creates a new UserManager / ApplicationDbContext per request. If this is true, then I would like to use the database context in my controllers / repositories. Is it possible to pass the database context into a controller? (Something to the lines of HttpResponse.GetOwinContext.Environment["owin.DatabaseContext"] ??)

There seems to be a half-finished question here that doesn't have an answer to the question: OWIN DbContext and a single DbContext for all of my Repositories. (also one here: Owin Context to use a single instance per request) Any guidance is appreciated.

Community
  • 1
  • 1
reZach
  • 8,945
  • 12
  • 51
  • 97

1 Answers1

1

Yes, this is true, you can setup your context to use the same instance of a class by using the method CreatePerOwinContext, so for the UserManager / ApplicationDbContext you can set them up in the Startup.ConfigureAuth method to something like this:

// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

and when you need your dependency you can use GetUserManager method for example to retrieve the ApplicationUserManager object. so something like this:

var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

Also, some Ioc containers like Autofac supports OWIN integration, you can refer to this webpage for more details.

Hope this helps.

Omar.Alani
  • 4,050
  • 2
  • 20
  • 31
  • Omar, is it possible to get this ApplicationDbContext when I am creating constructors? Such that I can grab this context, create the proper repository, and pass in the repository into the controller? – reZach Dec 14 '14 at 16:41
  • Well, if you have the OWIN context then you can call context.Get() for example to get the ApplicationDbContext for the current request after you registered that using app.CreatePerOwinContext in the Startup, you can have a look into my article http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En and check how do I call context.Get() when I initialize ApplicationUserManager class. – Omar.Alani Dec 15 '14 at 05:19