Multiple Interface injection with castle windsor

后端 未结 3 611
误落风尘
误落风尘 2020-12-29 00:23

How can you get castle Windsor to choose the right implantation of a interface at run time when you have multiple implementations in the container.

For example lets

3条回答
  •  梦谈多话
    2020-12-29 01:07

    As David said, you can't, but IHandlerSelector will let you take control. Check out the tests to get an idea of how to use them: https://svn.castleproject.org/svn/castle/trunk/InversionOfControl/Castle.Windsor.Tests/HandlerSelectorsTestCase.cs

    Basically, you would do something like:

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

    and then you register it with:

    container.Kernel.AddHandlerSelector(new WritenExamHandler());
    

    This will allow you to easily deal with multi-tenency issues :)

提交回复
热议问题