在Unity中的类型之间共享生命周期管理器? [英] Share lifetime managers between types in Unity?

查看:108
本文介绍了在Unity中的类型之间共享生命周期管理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Unity文档中看到的示例让您通过内联 new LifetimeManager()来指定生命周期管理器。所以我有这段代码:

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);

看似显而易见,但通过PDF阅读所有示例均采用了以前的样式,没有评论,所以我我想知道我是否不了解它的工作原理。

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.

说明:在执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中起源的详细信息。

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.

异常详细信息:System.InvalidOperationException:生命周期管理器已注册。终身管理员不能重复使用,请创建一个新的管理员。

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

这篇关于在Unity中的类型之间共享生命周期管理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆