与需要参数的工厂方法统一 [英] Unity with factory method who need parameters
问题描述
我想用需要参数的工厂方法在Unity容器中注册一个类型.这些参数应统一解决,但只能在运行时解决.
I want to register a type in an Unity container with a factory method who needs paramters. These parameters are to be resolved by unity but only at runtime.
工厂方法代码:
public static IApp Create(IOne, ITwo) {...}
注册代码:
container.RegisterType(typeof(IApp), new InjectionFactory(f => App.Create(???, ???)));
我需要替换"???"吗? ?
What do I need to replace the '???' ?
更多信息:
我的Unity配置分为两个阶段.第一阶段(应用程序正在启动),我注册了除一个对象之外的所有对象:
My Unity configuration is made in two phases. First phase (application is starting), I register all my object but one :
container.RegisterType<IOne, One>();
container.RegisterType<ITwo, Two>();
container.RegisterType<IApp, App>();
// ...
第二阶段(用户正在登录),我只注册一个上下文对象的实例,该实例在我所有类(One
,Two
,App
,...)的构造函数中使用:
Phase two (user is logging), I juste register an instance of a context object who is used in constructor of all my classes (One
, Two
, App
, ...) :
var childContainer = container.CreateChildContainer();
childContainer.RegisterInstance<AppEnvironment>(new AppEnvironment(userName));
这是我的代码,不使用InjectionFactory.它工作正常.现在,我必须多次注册IApp接口,并每次都调用一个不同的静态方法.静态方法示例:
This is my code without using InjectionFactory. It works fine. Now, I have to register multiple times my IApp interface, with calling a different static method each time. Example of static method :
public static IApp Create(IOne one, ITwo two, AppEnvironment env)
{
_one = one;
_two = two;
_env = env;
}
如果我向IApp注册此代码,则该代码:
If I register IApp this this code :
container.Register(typeof(IApp), new InjectionFactory(f => App.Create(container.Resolve<IOne>(), container.Resolve<ITwo>(), container.Resolve<AppEnvironment>()));
然后未设置我的env变量.
Then my env variable is not set.
但是,如果我注册了我的env实例(仅出于测试目的,我不能这样做),
But if I register my env instance (just for test purpose, I can't do that in my case), it works.
推荐答案
最后得到了解决方案.看起来像威利斯一世:
Finally got the solution. It looks like willys one :
container.RegisterType<IApp, App>(
new InjectionFactory(
f => App.Create(
f.Resolve<IOne>(),
f.Resolve<ITwo>()
)
)
);
这篇关于与需要参数的工厂方法统一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!