问题描述
使用MVVM的SimpleIoc,我想注册一个给定的接口的实现,但实现需要在其构造一个参数:
公共类MyServiceImplementation:IMyService {
公共MyServiceImplementation(字符串contructorString){...}
}
我希望注册接口的实现会的工作,但是,当它尝试解析接口SimpleIoc不考虑暗示。
SimpleIoc.Default.Register< MyServiceImplementation>(()=> {
返回新MyServiceImplementation(的Hello World);
});
SimpleIoc.Default.Register< IMyService,MyServiceImplementation>();
会不会有一种用SimpleIoc做到这一点,或者我应该考虑使用更完整的Ioc?
编辑::该做的伎俩,但我仍然不知道为什么上面的格式不工作
SimpleIoc.Default.Register< IMyService>(()=> {
返回新MyServiceImplementation(的Hello World);
} );
为什么你的第一种方法是不工作的原因是, SimpleIOC不使用本身来构造对象。
由于你的宣言
SimpleIoc.Default.Register< MyServiceImplementation> (()=> {
返回新MyServiceImplementation(的Hello World);
});
SimpleIoc.Default.Register< IMyService,MyServiceImplementation>();
要调用 SimpleIoc.Default.GetInstance< MyServiceImplementation>()
将执行工厂方法,而调用 SimpleIoc.Default.GetInstance< IMyService>()
不会。
一个可能的方式链的调用可以指定这两种类型的工厂方法, IMyService
和 MyServiceImplementation
,即
SimpleIoc.Default.Register< MyServiceImplementation>(()= > {
返回新MyServiceImplementation(的Hello World);
});
SimpleIoc.Default.Register< IMyService>(()=> {
返回SimpleIoc.Default.GetInstance< MyServiceImplementation>();
});
Using MVVM's SimpleIoc, I would like to register an implementation for a given interface, but the implementation requires one parameter in its constructor:
public class MyServiceImplementation : IMyService {
public MyServiceImplementation(string contructorString) { ... }
}
I was hoping that registering the implementation of the interface would work, but SimpleIoc doesn't consider the hint when it tries to resolve the interface.
SimpleIoc.Default.Register<MyServiceImplementation>(() => {
return new MyServiceImplementation("Hello World");
});
SimpleIoc.Default.Register<IMyService, MyServiceImplementation>();
Would there be a way to do this with SimpleIoc, or should I consider using a more complete Ioc?
Edit: This does the trick, but I still wonder why the form above doesn't work.
SimpleIoc.Default.Register<IMyService>(() => {
return new MyServiceImplementation("Hello World");
});
The reason why your first approach is not working is that SimpleIOC does not use itself to construct the objects.
Given your declaration
SimpleIoc.Default.Register<MyServiceImplementation>(() => {
return new MyServiceImplementation("Hello World");
});
SimpleIoc.Default.Register<IMyService, MyServiceImplementation>();
The call to SimpleIoc.Default.GetInstance<MyServiceImplementation>()
will execute the factory method, while the call to SimpleIoc.Default.GetInstance<IMyService>()
won't.
A possible way to chain the calls could be to specify a factory method for both types, IMyService
and MyServiceImplementation
, i.e.
SimpleIoc.Default.Register<MyServiceImplementation>(() => {
return new MyServiceImplementation("Hello World");
});
SimpleIoc.Default.Register<IMyService>(() => {
return SimpleIoc.Default.GetInstance<MyServiceImplementation>();
});
这篇关于MVVM SimpleIoc,如何使用接口时,该接口实现需要施工参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!