0
背景:定的接口,實現和消費者是否可以向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) { /* .. */ }
}
那麼容易配置的溫莎注入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) { /* .. */ }
}
然後是有可能溫莎配置以注入LengthDoer.DoIt
作爲一個實例方法委託其中LengthDoer
具有PerWebRequest
生活方式,使得溫莎可以跟蹤併發布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);
}
哇!令人驚訝和意外的是,溫莎追蹤工廠方法中的分辨率。換句話說,如果'LengthDoer'實現'IDisposable',那麼當你解析''釋放''DoItFunc'時,Windsor將在綁定的'LengthDoer'實例上調用Dispose。這是意想不到的,因爲KrzysztofKoźmic寫道您必須發佈在工廠方法中解決的所有組件。 http://kozmic.net/2010/08/27/must-i-release-everything-when-using-windsor/謝謝。 –