我有以下代码:
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()));
我不确定是否会这样做,或者这只是我做第一段代码片段的旧方法。
任何建议都会很棒!
答案 0 :(得分:5)
您在那里运行的代码运行一次 - 在注册时创建一个CustomerEntities对象,该实例作为后来解析的所有GenericRepository对象的参数共享。
如果你想为每个GenericRepository实例提供一个单独的CustomerEntities实例,那就非常简单了 - 只需让容器完成提升。在注册中,请执行以下操作:
IOC.Container.RegisterType<IRepository, GenericRepository>("Customers",
new InjectionConstructor(typeof(CustomerEntities)));
这将告诉容器“在解析IRepository时,创建一个GenericRepository实例。调用带有单个CustomerEntities参数的构造函数。通过容器解析该参数。
这应该可以解决问题。如果您需要在容器中进行特殊配置以解析CustomerEntities,只需使用单独的RegisterType调用即可。
您展示的第二个示例是Unity 1.0中过时的API。不要使用它,它现在不能完成任何比RegisterType更多的事情。