Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c# - 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:

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");
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...