Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share lifetime managers between types in Unity?

The examples I've seen in the Unity documentation have you specifying the lifetime manager by putting new LifetimeManager() inline. So I have this code:

container.RegisterType<ApplicationDbContext>(new PerRequestLifetimeManager());

container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new PerRequestLifetimeManager(),
          new InjectionConstructor(typeof (ApplicationDbContext)));

container.RegisterType<UserManager<ApplicationUser>>(new PerRequestLifetimeManager());

Fine, but I wonder why I'm creating so many instances. Is there any reason why I shouldn't write it like this instead?

var lifetimeManager = new PerRequestLifetimeManager();

container.RegisterType<ApplicationDbContext>(lifetimeManager);

container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(lifetimeManager,
          new InjectionConstructor(typeof (ApplicationDbContext)));

container.RegisterType<UserManager<ApplicationUser>>(lifetimeManager);

It seems obvious but reading through the PDF all the examples are in the former style without comment so I'm wondering if I'm not understanding something about how it works.

like image 944
Casey Avatar asked Mar 25 '14 15:03

Casey


1 Answers

No, you can't do this. You'll find that your application throws an exception if you try:

The lifetime manager is already registered. Lifetime managers cannot be reused, please create a new one.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The lifetime manager is already registered. Lifetime managers cannot be reused, please create a new one.

like image 59
Casey Avatar answered Sep 28 '22 12:09

Casey