How to return an instance based on its parent using Simple Injector?

徘徊边缘 提交于 2019-12-11 05:56:13

问题


We have been using Windsor Castle as our DI Container but we are looking around for alternatives. Now I got to the Simple Injector and so far I have been impressed by its simplicity but one scenario I am stuck at right now is when we are using late bound instantiation for some of our components.

My first question is, is it even possible?

With Windsor it is done like this;

Container.Register(Component.For<ILogger>()
    .UsingFactoryMethod(
        (kernel, componentModel, context) => new Logger(
            context.Handler.ComponentModel.Implementation.Name));

Is there a way to do the same with Simple Injector?


回答1:


With Simple Injector, you will just have to either:

  1. Register a Func delegate explicitly using Register<Func<A, B, C>>((a, b) => { ... })
  2. Create an interface such as ILoggerFactory, creste an implementation and register them.

UPDATE

After reading your question again and looking up the definition of Castle's UsingFactoryMethod I came to the conclusion that I misinterpreted your question. What you are looking for is creating an instance based on its parent type: Context Based Injection.

You can achieve this by implementing the Context Based Injection Extension method that is given as example on the Simple Injector's documentation wiki.

When you add this extension method to your project you can do the equivalent registration as follows:

container.RegisterWithContext<ILogger>(context =>
{
    return new Logger(context.ImplementationType.Name);
});


来源:https://stackoverflow.com/questions/13675137/how-to-return-an-instance-based-on-its-parent-using-simple-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!