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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With