Unity InjectionConstructor何时在何时运行? [英] When is the Unity InjectionConstructor acually run?

查看:74
本文介绍了Unity InjectionConstructor何时在何时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

IOC.Container.RegisterType<IRepository, GenericRepository>
              ("Customers", new InjectionConstructor(new CustomerEntities()));

我想知道的是,是否在类型注册发生时调用new CustomerEntities()一次,或者是否每次解析IRepository(名称为"Customers")时都将创建一个新的CustomerEntities.

What I am wondering is if the new CustomerEntities() will be called once when the type registration happens OR if every time IRepository (with name "Customers") is resolved a new CustomerEntities will be made.

如果不是后者,那么是否有办法使它更像委托一样工作? (那么它每次解决都会产生一个新的吗?)

If it is not the latter, then is there a way to make it work more like a delegate? (So it will make a new one every time it Resolves?)

我找到了以下代码:

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

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

I am not sure if that would do it or if that is just an old way of doing what my first code snippet does.

任何建议都会很棒!

推荐答案

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

The code you have there runs once - a single CustomerEntities object is created at registration time, and that instance is shared as the parameter across all GenericRepository objects resolved later.

如果您要为GenericRepository的每个实例单独创建一个CustomerEntities实例,那很容易-只需让容器进行提升即可.在注册中,执行以下操作:

If you want a separate instance of CustomerEntities for each instance of GenericRepository, that's pretty easy - just let the container do the lifting. In the registration, do this:

IOC.Container.RegisterType<IRepository, GenericRepository>("Customers", 
    new InjectionConstructor(typeof(CustomerEntities)));

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

This will tell the container "When resolving IRepository, create an instance of GenericRepository. Call the constructor that takes a single CustomerEntities parameter. Resolve that parameter through the container.

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

This should do the trick. If you need to do special configuration in the container to resolve CustomerEntities, just do that with a separate RegisterType call.

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

The second example you showed is the obsolete API from Unity 1.0. Don't use it, it doesn't accomplish anything more than you can do with RegisterType now.

这篇关于Unity InjectionConstructor何时在何时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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