質問

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.

他のヒント

IIRC, a Unity lifetime is simply a class that derives from the abstract LifetimeManager class, and you can reuse objects.

In my book, in chapter 14, I show a complex example of building a custom lifetime manager for Unity, and finally register it like this:

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

Unless Unity's lifetime management architecture has changed significantly since I looked at it, I see no reason to create a new PerRequestLifetimeManager instance every time you register something.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top