Is it possible to inject an instance method delegate from a non-singleton component with Castle Windsor?

StackOverflow https://stackoverflow.com/questions/22366982

Pregunta

Background: Given interface, implementation, and consumer

public interface IDoer {
    int DoIt(string arg);
}

public class LengthDoer : IDoer { 
    int _internalState;
    public LengthDoer(IDependency dep) { _internalState = dep.GetInitialValue(); }
    public int DoIt(string arg) { 
        _internalState++;
        return arg.Length;
    }
}

public class HighLevelFeature {
    public HighLevelFeature(IDoer doer) { /* .. */ }
}

then it is straightforward to configure Windsor to inject Doer into HighLevelFeature upon construction, where LengthDoer has a PerWebRequest lifestyle.

Problem: However, if the design were to change to

public delegate int DoItFunc(string arg);

// class LengthDoer remains the same, without the IDoer inheritance declaration

public class HighLevelFeature {
    public HighLevelFeature(DoItFunc doer) { /* .. */ }
}

then is it possible to configure Windsor to inject LengthDoer.DoIt as an instance method delegate where LengthDoer has PerWebRequest lifestyle, such that Windsor can track and Release LengthDoer instances? In other words, Windsor would mimic:

// At the beginning of the request
{
    _doer = Resolve<LengthDoer>();
    return _hlf = new HighLevelFeature(doer.DoIt);
}

// At the end of the request
{
    Release(_doer);
    Release(_hlf);
}
¿Fue útil?

Solución

DoItFunc delegate can be registered using UsingFactoryMethod:

container.Register(Component.For<IDoer>().ImplementedBy<LengthDoer>());
container.Register(Component.For<DoItFunc>()
    .UsingFactoryMethod(kernel =>
        {
            return new DoItFunc(kernel.Resolve<IDoer>().DoIt);
        }));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top