In Asp.Net MVC, the default template comes with Startup class in Startup.Auth.cs
public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); According to the comment in this template, an instance of ApplicationDbContext is created per request.
In my application, I am using the Repository Pattern and inject ApplicationDbContext into the repositories. In my case I am using Ninject, which can share the same context among multiple repositories if needed.
Is there any way to use the same injected ApplicationDbContext in Startup.Auth? Not really sure if this is a good idea to change the default template, at the same time we are creating 2 instances of the same context in 1 request...
In my Ninject code, I am binding ApplicationDbContext to itself as below:
private static void RegisterServices(IKernel kernel) { kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope(); Not really sure if this a bad practice to bind the context to itself instead of creating an interface? (though it is working fine).
Startup.Authwhen you can just callApplicationDbContext.Create()to get an instance. Just don't forget to dispose of it when done. Just because you are using DI, does not mean you should inject stuff into every (im)possible place.ConfigureAuthis executed on the application startup, possibly even before you have your Ninject container initialised. And it will go out of scope before you'll have any http requests, so no chance to have clashing dbContext instances.