背景:给定接口,实现和消费者
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);
}
答案 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);
}));