I noticed the project template for MVC when using individual user accounts puts a few objects in the current Owin context (in App_Start/Startup.Auth.cs):
// 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);
It looks like this is to access the database for Identity features. My understanding is that a single instance of ApplicationDbContext is created per request and re-used through the entire pipeline. Would it be beneficial to do the same with my own entity framework DbContexts?
For example I created a new file in App_Start/Startup.Data.cs:
public partial class Startup
{
public void ConfigureData(IAppBuilder app)
{
app.CreatePerOwinContext(CreateParkingEntities);
}
protected ParkingEntities CreateParkingEntities()
{
return new ParkingEntities();
}
}
Then in Startup.cs:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
ConfigureData(app);
}
}
Then I can use the context in my controllers:
private ParkingEntities _db;
public ParkingEntities DbContext
{
get
{
return _db ?? HttpContext.GetOwinContext().Get<ParkingEntities>();
}
private set
{
_db = value;
}
}
I would think if this was standard practice, the entity framework would have some scaffolding for this, but it just creates an instance at the controller level. Is it safe to assume that if DbContext is only accessed from that controller then it would be functionally equivalent to the above implementation and placing it in the Owin pipeline is overkill?
I suppose another use of this approach is a single initialization point for the DbContext, if additional setup is needed.