Unity InjectionConstructor什么时候运行?
本文关键字:运行 什么时候 InjectionConstructor Unity | 更新日期: 2023-09-27 18:05:10
我有以下代码:
IOC.Container.RegisterType<IRepository, GenericRepository>
("Customers", new InjectionConstructor(new CustomerEntities()));
我想知道的是,如果new CustomerEntities()
将在类型注册发生时被调用一次,或者如果每次IRepository(名称为"Customers")被解析,则将制作一个新的CustomerEntities。
如果不是后者,那么是否有一种方法可以使它更像委托?(所以它会在每次解析时创建一个新的?)
我找到了这个代码:
IOC.Container.RegisterType<IRepository, GenericRepository>("Customers")
.Configure<InjectedMembers>()
.ConfigureInjectionFor<ObjectContext>
(new InjectionConstructor(new CustomerEntities()));
我不确定这是否会做到这一点,或者这只是我的第一个代码片段所做的旧方法。
任何建议都会很好!
这里的代码只运行一次—在注册时创建单个CustomerEntities对象,并且该实例作为参数在以后解析的所有GenericRepository对象之间共享。
如果您希望为GenericRepository的每个实例提供一个单独的CustomerEntities实例,这非常简单—只需让容器完成这项工作即可。在注册中,这样做:
IOC.Container.RegisterType<IRepository, GenericRepository>("Customers",
new InjectionConstructor(typeof(CustomerEntities)));
这将告诉容器"当解析IRepository时,创建GenericRepository的实例。"调用接受单个CustomerEntities参数的构造函数。通过容器解析该参数。
这应该能奏效。如果你需要在容器中做特殊的配置来解析CustomerEntities,只需要用一个单独的RegisterType调用来做。
你展示的第二个例子是Unity 1.0中过时的API。不要使用它,它不会比现在的RegisterType完成更多的事情。