当您在容器中有多个实现时,如何让Castle Windsor在运行时选择正确的接口植入.
例如,假设我有一个名为IExamCalc的简单界面,它可以计算出某人在该考试中的表现.
不,我们有几个像这样的实现,例如,
public interface IExamCalc { int CalculateMark(ExamAnswers examAnswers) } public class WritenExam : IExamCalc { public int CalculateMark(ExamAnswers examAnswers) { return 4; } } public class OralExam : IExamCalc { public int CalculateMark(ExamAnswers examAnswers) { return 8; } } public class ExamMarkService { private IExamCalc _examCalc; public ExamMarkService(IExamCalc examCalc) { _examCalc = examCalc; } public int[] CalculateExamMarks(ExamAnswers[] examAnswers) { IListmarks = new List ; foreach(ExamAnswers examanswer in examaAnswers) { marks.Add(_examCalc.CalculateMark); } } }
假设通过Windor恢复了ExamMarkService如何确保在构造函数中注入正确的实现,这是多租户问题的一个例子吗?
希望一切都有所作为
科林G.
正如大卫所说,你不能,但IHandlerSelector将让你掌控.查看测试以了解如何使用它们:https://svn.castleproject.org/svn/castle/trunk/InversionOfControl/Castle.Windsor.Tests/HandlerSelectorsTestCase.cs
基本上,你会做类似的事情:
public class WritenExamHandler : IHandlerSelector { public bool HasOpinionAbout(string key, Type service) { // Decision logic here return somethingThatWouldBeTrueToSelectWritenExam && service == typeof(IExamCalc); } public IHandler SelectHandler(string key, Type service, IHandler[] handlers) { return handlers.Where(handler => handler.ComponentModel.Implementation == typeof (WritenExam)).First(); } }
然后你注册它:
container.Kernel.AddHandlerSelector(new WritenExamHandler());
这将使您轻松处理多个问题:)