【问题标题】:Is it possible to inject an instance method delegate from a non-singleton component with Castle Windsor?是否可以使用 Castle Windsor 从非单例组件注入实例方法委托?
【发布时间】:2014-04-17 12:00:16
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    DoItFunc委托可以使用UsingFactoryMethod注册:

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

    【讨论】:

    • 哇!令人惊讶和出乎意料的是,Windsor 在工厂方法中跟踪解决方案。换句话说,如果LengthDoer 实现了IDisposable,那么当你Resolve+Release 一个DoItFunc 时,Windsor 将在绑定的LengthDoer 实例上调用Dispose。这是出乎意料的,因为 Krzysztof Koźmic 写道,您必须释放在工厂方法中解析的所有组件。 kozmic.net/2010/08/27/… 谢谢。
    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多