简体   繁体   English

Castle Windsor - 使用工厂方法注册所有接口

[英]Castle Windsor - Register all interfaces with factory method

I have a number of interfaces: 我有很多接口:

  • IFirstProvider
  • ISecondProvider
  • IThirdProvider
  • etc.. 等等..

I'm trying to register all these interfaces so that they use a factory method to get the instance: 我正在尝试注册所有这些接口,以便他们使用工厂方法来获取实例:

container.Register
    (  
        AllTypes
            .FromThisAssembly()
            .Where(t => t.IsInterface && t.Name.EndsWith("Provider"))
            .Configure(c => c.UsingFactoryMethod(f => f.Resolve<DictionaryAdapterFactory>().GetAdapter<object>(c.ServiceType, session))
    );

But this doesn't seem to work. 但这似乎不起作用。 Instead, I have to use a for loop to register all these interfaces: 相反,我必须使用for循环来注册所有这些接口:

List<Type> providers = new List<Type>
    (
        Assembly
            .GetExecutingAssembly()
            .GetTypes()
            .Where(x => x.IsInterface && x.Name.EndsWith("Provider"))
    );

foreach (Type provider in providers)
{
    Type temp = provider;

    container.Register
        (
            Component
                .For(temp)
                .UsingFactoryMethod(f => f.Resolve<DictionaryAdapterFactory>().GetAdapter<object>(temp, session))
        );
}

Is there a better way to register these interfaces besides using a for loop? 除了使用for循环之外,还有更好的方法来注册这些接口吗?

There's no better built in way in Windsor < 3.0 在Windsor <3.0中没有更好的内置方式

As of Windsor 3, you can do it using Types , instead of AllTypes . 从Windsor 3开始,您可以使用Types而不是AllTypesAllTypes

AllTypes really means all non abstract classes AllTypes实际上意味着所有非抽象类

Types really means all types. Types真的意味着所有类型。

Yes, while this does slightly suck and is counterintuitive, since AllTypes came first, we couldn't change its existing behavior to maintain backward compatibility. 是的,虽然这确实有点吮吸并且是违反直觉的,但由于AllTypes排在第一位,我们无法改变其现有行为以保持向后兼容性。 Also to maintain sanity it is recommended to use Classes instead of AllTypes , so you'll end up registering either Classses for classes and Types for cases like this one in your question. 另外,为了保持理智,建议使用Classes而不是AllTypes ,因此您最终会在类问题中为类似案例注册ClasssesTypes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM