Share lifelong managers between types in Unity?

In the examples I saw in the Unity documentation, you specify the lifecycle manager by inserting 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()); 

Good, but I wonder why I create so many instances. Is there a reason why I shouldn't write it like this?

 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 PDF all the examples in the previous style without comment, so I wonder if I don't understand something about how this works.

+6
source share
2 answers

No, you cannot do this. You will find that your application throws an exception if you try:

The lifecycle manager is already registered. Lifetime managers cannot be reused; create a new one.

Description: An unhandled exception occurred during the execution of the current web request. View the stack trace for more information about the error and its occurrence in the code.

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

+4
source

IIRC, Unity's lifetime is just a class that comes from the abstract LifetimeManager class, and you can reuse objects.

In my book , in chapter 14, I show a complex example of creating a custom time manager for Unity and finally register it

 var lease = new SlidingLease(TimeSpan.FromMinutes(1)); var cache = new CacheLifetimeManager(lease); container.RegisterType<IIngredient, Parsley>(cache); 

If the Unity lifecycle management architecture has not changed significantly since I looked at it, I see no reason to create a new instance of PerRequestLifetimeManager every time you register something.

+1
source

All Articles