sti*_*k81 13 .net c# prism unity-container
我正在使用Prism,它也是很好的Unity IoC容器.我是这个概念的新手,所以我还没有全力以赴.我现在要做的是使用IoC容器创建一个对象,但也传递一个额外的参数.请允许我用一个例子解释..:
我有一个接受命令对象的类.这是在IoC容器中注册的,因此它可以很好地处理它:
public class Person
{
public Person(IApplicationCommands commands) { .. }
..
}
Person person = _container.Resolve<Person>();
Run Code Online (Sandbox Code Playgroud)
现在 - 我想传递另一个论点 - 例如人的名字.但是,我仍然希望使用IoC容器来处理解析,从而从IoC容器中获取其他参数.但是将名称作为"自定义"参数传递.可以这样做吗?
public class Person
{
public Person(IApplicationCommands commands, string name) { .. }
..
}
string name = "John";
Person person = _container.Resolve<Person>(name); // ....??
Run Code Online (Sandbox Code Playgroud)
这个例子似乎不起作用,但有没有办法让它工作?或者Unity IoC容器是否要求在调用Resolve之前在容器中注册所有参数?
Not*_*Dan 18
我可以将构造函数参数传递给Unity的Resolve()方法吗?
container.Resolve<IFoo>(new ParameterOverrides<Foo> { { "name", "bar" }, { "address", 42 } });"
Run Code Online (Sandbox Code Playgroud)
编辑:在我看来,这个答案是过时的,因为它假设有较旧版本的Unity.NotDan的答案更好.
你有几个选择.他们老实说有点蹩脚,但他们会工作.
选项1:Scoped Container
如果要使用构造函数注入,则需要创建一个作用域容器并将数据放入该作用域容器中:
IUnityContainer subContainer = _container.CreateChildContainer();
//Don't do this... create a custom type other than string, like
// MyConstructorParams or something like that... this gets the point across.
subContainer.RegisterInstance<string>("John");
Person person = subContainer.Resolve<Person>();
Run Code Online (Sandbox Code Playgroud)
选项2:初始化方法
但是,我通常会在目标对象上为实例变量设置一个单独的Initialize方法:
Run Code Online (Sandbox Code Playgroud)public class Person { public Person(IApplicationCommands commands) { .. } public void Initialize(string name) { .. } .. }
然后你的用法变成:
Person person = container.Resolve<Person>();
person.Initialize("John");
Run Code Online (Sandbox Code Playgroud)
两者都不是特别令人愉快,但它会完成工作.重要的是选择一个约定并坚持下去,否则你会有点迷失.
希望这可以帮助.
归档时间: |
|
查看次数: |
13834 次 |
最近记录: |