12

不确定这是否可能。

我需要根据枚举值返回服务的正确实现。所以手工编码的实现看起来像:

public enum MyEnum
{
  One,
  Two
}    

public class MyFactory
{
  public ITypeIWantToCreate Create(MyEnum type)
  {
    switch (type)
    {
       case MyEnum.One
           return new TypeIWantToCreate1();
           break;
       case MyEnum.Two
           return new TypeIWantToCreate2();
           break;
       default:
           return null;       
    }    
  }
}

返回的实现具有额外的依赖项,需要通过容器注入,因此手动工厂将无法工作。

这可能吗?如果可以,注册会是什么样子?

4

2 回答 2

8

如果将您的组件注册到将枚举值指定为组件 id 的容器中是一种选择,您也可以考虑这种方法

 public class ByIdTypedFactoryComponentSelector : DefaultTypedFactoryComponentSelector
 {
      protected override string GetComponentName(MethodInfo method, object[] arguments)
      {
            if (method.Name == "GetById" && arguments.Length > 0 && arguments[0] is YourEnum)
            {
                 return (string)arguments[0].ToString();
            }

            return base.GetComponentName(method, arguments);
      }
}

比 ByIdTypedFactoryComponentSelector 将用作您的类型化工厂的选择器

public enum YourEnum
{
    Option1
}

public IYourTypedFactory
{
    IYourTyped GetById(YourEnum enumValue)
}


container.AddFacility<TypedFactoryFacility>();
container.Register
(       
    Component.For<ByIdTypedFactoryComponentSelector>(),

    Component.For<IYourTyped>().ImplementedBy<FooYourTyped>().Named(YourEnum.Option1.ToString()),

    Component.For<IYourTypedFactory>()
    .AsFactory(x => x.SelectedWith<ByIdTypedFactoryComponentSelector>())
    .LifeStyle.Singleton,

    ...
于 2012-10-04T09:45:25.073 回答
1

看起来这是可能的。看看这个:

例子

您将需要创建一个 ITypedFactoryComponentSelector 实现来解析调用,并将其注册到容器中以仅解析您感兴趣的类的调用。

于 2012-10-03T15:49:54.527 回答