Multiple Interface injection with castle windsor

后端 未结 3 582
误落风尘
误落风尘 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 00:56

    Multi-tenancy is defined as being able to run your software on one instance, serving multiple tenants/customers/clients. I guess you could run into problems like yours more often in a multi-tenancy setup.

    All your components have keys which are unique strings, so you may always so a container.Resolve("someKey") to get a specific implementation.

    If you want to have a specific implementation automatically injected, you may configure your component like this (off my memory, may not be 100% precise):

    <component id="someService.customer1" service="ISomeService" type="Customer1SomeService" />
    
    <component id="anotherId" service="IAnotherService" type="AnotherService">
        <parameters>
            <parameterName> <!-- as written in the ctor's signature -->
               ${someService.customer1}
            </parameterName>
        </parameters> 
    </component>
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-12-29 01:10

    The short answer is, you can't. This kind of choice is dependent on application code, so if you just did container.Resolve<IExamCalc>, then Windsor couldn't know which one you wanted.

    The question to ask is how do you know which type to use?

    0 讨论(0)
提交回复
热议问题