Castle Windsor: How do you add a call to a factory facility not in xml?

只愿长相守 提交于 2019-12-06 14:18:23

问题


I know how to tell Castle Windsor to resolve a reference from a factory's method using XML, but can I do it programmatically via the Container.AddComponent() interface? If not is there any other way to do it from code?

EDIT: There seems to be some confusion so let me clarify, I am looking for a way to do the following in code:

<facilities>
   <facility
        id="factory.support"
        type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.MicroKernel"
    />

</facilities>

<components>

    <component
        id="CustomerRepositoryFactory"
        type="ConsoleApplication2.CustomerRepositoryFactory, ConsoleApplication2"
    />

    <component
        id="CustomerRepository"
        service="ConsoleApplication2.ICustomerRepository, ConsoleApplication2"
        type="ConsoleApplication2.CustomerRepository, ConsoleApplication2"
        factoryId="CustomerRepositoryFactory"
        factoryCreate="Create"
    />

</components>

(from this codebetter article on factory support in windsor and spring.net)


回答1:


Directly from the Unit Test FactorySupportTestCase (which are your friends):

[Test]
    public void FactorySupport_UsingProxiedFactory_WorksFine()
    {
        container.AddFacility("factories", new FactorySupportFacility());
        container.AddComponent("standard.interceptor", typeof(StandardInterceptor));
        container.AddComponent("factory", typeof(CalulcatorFactory));

        AddComponent("calculator", typeof(ICalcService), typeof(CalculatorService), "Create");

        ICalcService service = (ICalcService) container["calculator"];

        Assert.IsNotNull(service);
    }

    private void AddComponent(string key, Type service, Type type, string factoryMethod)
    {
        MutableConfiguration config = new MutableConfiguration(key);
        config.Attributes["factoryId"] = "factory";
        config.Attributes["factoryCreate"] = factoryMethod;
        container.Kernel.ConfigurationStore.AddComponentConfiguration(key, config);
        container.Kernel.AddComponent(key, service, type);
    }


来源:https://stackoverflow.com/questions/64238/castle-windsor-how-do-you-add-a-call-to-a-factory-facility-not-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!