Registering ApplicationDbContext with hierarchical lifetime manager












0














I'm starting from an out-of-the-box MVC5 installation and Unity as an IoC container.



using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Data.Entity;
using System.Web;
using DemoAPI.Repository;
using DemoMVC.Controllers;
using DemoMVC.Models;
using Unity;
using Unity.AspNet.Mvc;
using Unity.Injection;
using Unity.Lifetime;

namespace DemoMVC
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});

/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion

/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{

container.RegisterType<IRepository, DemoRepository>();

#region OWIN
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>,
UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());
#endregion



}
}
}


I have one major worry here: Registering ApplicationDbContext with hierarchical lifetime manager. Manually registering DbContext and using this instance when registering the rest of the types - seems fishy to use the same eternal db context for ALL requests. However, per request makes even less sense for me, as it seems a huge waste of resources to instantiate dbContext per every request.



Is there another/better way to do this that I might be missing? I tried looking up the docs for unity and particularly lifetime managers, but everything I could find seems fairly outdated.










share|improve this question


















  • 1




    Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
    – Camilo Terevinto
    Nov 23 at 0:47
















0














I'm starting from an out-of-the-box MVC5 installation and Unity as an IoC container.



using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Data.Entity;
using System.Web;
using DemoAPI.Repository;
using DemoMVC.Controllers;
using DemoMVC.Models;
using Unity;
using Unity.AspNet.Mvc;
using Unity.Injection;
using Unity.Lifetime;

namespace DemoMVC
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});

/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion

/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{

container.RegisterType<IRepository, DemoRepository>();

#region OWIN
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>,
UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());
#endregion



}
}
}


I have one major worry here: Registering ApplicationDbContext with hierarchical lifetime manager. Manually registering DbContext and using this instance when registering the rest of the types - seems fishy to use the same eternal db context for ALL requests. However, per request makes even less sense for me, as it seems a huge waste of resources to instantiate dbContext per every request.



Is there another/better way to do this that I might be missing? I tried looking up the docs for unity and particularly lifetime managers, but everything I could find seems fairly outdated.










share|improve this question


















  • 1




    Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
    – Camilo Terevinto
    Nov 23 at 0:47














0












0








0







I'm starting from an out-of-the-box MVC5 installation and Unity as an IoC container.



using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Data.Entity;
using System.Web;
using DemoAPI.Repository;
using DemoMVC.Controllers;
using DemoMVC.Models;
using Unity;
using Unity.AspNet.Mvc;
using Unity.Injection;
using Unity.Lifetime;

namespace DemoMVC
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});

/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion

/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{

container.RegisterType<IRepository, DemoRepository>();

#region OWIN
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>,
UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());
#endregion



}
}
}


I have one major worry here: Registering ApplicationDbContext with hierarchical lifetime manager. Manually registering DbContext and using this instance when registering the rest of the types - seems fishy to use the same eternal db context for ALL requests. However, per request makes even less sense for me, as it seems a huge waste of resources to instantiate dbContext per every request.



Is there another/better way to do this that I might be missing? I tried looking up the docs for unity and particularly lifetime managers, but everything I could find seems fairly outdated.










share|improve this question













I'm starting from an out-of-the-box MVC5 installation and Unity as an IoC container.



using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Data.Entity;
using System.Web;
using DemoAPI.Repository;
using DemoMVC.Controllers;
using DemoMVC.Models;
using Unity;
using Unity.AspNet.Mvc;
using Unity.Injection;
using Unity.Lifetime;

namespace DemoMVC
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});

/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion

/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{

container.RegisterType<IRepository, DemoRepository>();

#region OWIN
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>,
UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());
#endregion



}
}
}


I have one major worry here: Registering ApplicationDbContext with hierarchical lifetime manager. Manually registering DbContext and using this instance when registering the rest of the types - seems fishy to use the same eternal db context for ALL requests. However, per request makes even less sense for me, as it seems a huge waste of resources to instantiate dbContext per every request.



Is there another/better way to do this that I might be missing? I tried looking up the docs for unity and particularly lifetime managers, but everything I could find seems fairly outdated.







c# entity-framework asp.net-mvc-5 owin unity-container






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 23:59









Milos Milosavljevic

629




629








  • 1




    Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
    – Camilo Terevinto
    Nov 23 at 0:47














  • 1




    Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
    – Camilo Terevinto
    Nov 23 at 0:47








1




1




Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
– Camilo Terevinto
Nov 23 at 0:47




Why creating a new instance of the context for each request would be a waste? FYI, this is what ASP.NET Core does out of the box, and it works quite great. Also, if you are worried about out of date stuff, leave MVC 5 behind
– Camilo Terevinto
Nov 23 at 0:47

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439246%2fregistering-applicationdbcontext-with-hierarchical-lifetime-manager%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439246%2fregistering-applicationdbcontext-with-hierarchical-lifetime-manager%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Lallio

Futebolista

Jornalista