是否可以从Castle Windsor的非单例组件中注入实例方法委托?

时间:2014-03-13 00:50:38

标签: c# oop functional-programming castle-windsor

背景:给定接口,实现和消费者

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) { /* .. */ }
}

然后可以直接配置Windsor在构建时Doer注入HighLevelFeature,其中LengthDoer具有PerWebRequest生活方式。

问题:但是,如果设计要更改为

public delegate int DoItFunc(string arg);

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

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

然后是否可以配置Windsor注入LengthDoer.DoIt作为实例方法委托LengthDoer具有PerWebRequest生活方式,,以便Windsor可以跟踪和释放LengthDoer实例?换句话说,温莎会模仿:

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

1 个答案:

答案 0 :(得分:1)

DoItFunc委托可以使用UsingFactoryMethod注册:

container.Register(Component.For<IDoer>().ImplementedBy<LengthDoer>());
container.Register(Component.For<DoItFunc>()
    .UsingFactoryMethod(kernel =>
        {
            return new DoItFunc(kernel.Resolve<IDoer>().DoIt);
        }));