问题
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:
- Register a Func delegate explicitly using
Register<Func<A, B, C>>((a, b) => { ... })
- 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