简体   繁体   English

MVVM SimpleIoc,当接口实现需要构造参数时如何使用接口

[英]MVVM SimpleIoc, how to use an interface when the interface implementation requires construction parameters

Using MVVM's SimpleIoc, I would like to register an implementation for a given interface, but the implementation requires one parameter in its constructor: 使用MVVM的SimpleIoc,我想为给定的接口注册一个实现,但是实现在它的构造函数中需要一个参数:

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在尝试解析接口时不考虑提示。

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? 有没有办法用SimpleIoc做到这一点,或者我应该考虑使用更完整的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. 您的第一种方法不起作用的原因是SimpleIOC不会使用它自己来构造对象。

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. SimpleIoc.Default.GetInstance<MyServiceImplementation>()的调用将执行工厂方法,而对SimpleIoc.Default.GetInstance<IMyService>()的调用则不会。

A possible way to chain the calls could be to specify a factory method for both types, IMyService and MyServiceImplementation , ie 链接调用的一种可能方法是为两种类型指定工厂方法, IMyServiceMyServiceImplementation ,即

SimpleIoc.Default.Register<MyServiceImplementation>(() => {
    return new MyServiceImplementation("Hello World");
});

SimpleIoc.Default.Register<IMyService>(() => {
    return SimpleIoc.Default.GetInstance<MyServiceImplementation>();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM