Unity InjectionConstructor何时正常运行?

Vac*_*ano 1 .net c# inversion-of-control unity-container

我有以下代码:

IOC.Container.RegisterType<IRepository, GenericRepository>
              ("Customers", new InjectionConstructor(new CustomerEntities()));
Run Code Online (Sandbox Code Playgroud)

我想知道的是,如果在new CustomerEntities()类型注册发生时将调用一次,或者如果每次IRepository(名称为"Customers")被解析,将会产生新的CustomerEntities.

如果它不是后者,那么有没有办法让它更像是一个代表呢?(所以每次它解决它会创建一个新的?)

我找到了这段代码:

IOC.Container.RegisterType<IRepository, GenericRepository>("Customers")
             .Configure<InjectedMembers>()
             .ConfigureInjectionFor<ObjectContext>
              (new InjectionConstructor(new CustomerEntities()));
Run Code Online (Sandbox Code Playgroud)

我不确定是否会这样做,或者这只是我做第一个代码片段的旧方法.

任何建议都会很棒!

Chr*_*res 6

您在那里运行的代码运行一次 - 在注册时创建一个CustomerEntities对象,并且该实例作为以后解析的所有GenericRepository对象的参数共享.

如果你想为GenericRepository的每个实例创建一个单独的CustomerEntities实例,那就非常简单 - 只需让容器完成提升.在注册中,执行以下操作:

IOC.Container.RegisterType<IRepository, GenericRepository>("Customers", 
    new InjectionConstructor(typeof(CustomerEntities)));
Run Code Online (Sandbox Code Playgroud)

这将告诉容器"在解析IRepository时,创建一个GenericRepository实例.调用带有单个CustomerEntities参数的构造函数.通过容器解析该参数.

这应该可以解决问题.如果您需要在容器中进行特殊配置以解析CustomerEntities,只需使用单独的RegisterType调用即可.

您展示的第二个示例是Unity 1.0中过时的API.不要使用它,它现在不能完成任何比RegisterType更多的事情.