我可以用类型化的工厂设备返回基于(枚举)参数实现? [英] Can I Use Typed Factory Facility to Return Implementation Based on (enum) Parameter?

查看:117
本文介绍了我可以用类型化的工厂设备返回基于(枚举)参数实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道这是可能的或没有。

Not sure if this is possible or not.

我需要回到正确执行基于一个枚举值的服务。因此,手工编码的实施看起来是这样的:

I need to return the correct implementation of a service based on an enum value. So the hand-coded implementation would look something like:

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



返回的实现具有这将需要更多依赖通过容器注入,所以手卷工厂将无法工作。

The implementations that are returned have additional dependencies which will need to be injected via the container, so a hand-rolled factory won't work.

这是可能的,如果是的话会是什么样子注册怎么样?

Is this possible, and if so what would the registration look like?

推荐答案

如果注册组件放入容器中指定的枚举值作为组件id是一个选项,你可能会考虑这种方法太

If registering your component into the container specifying the enum value as component id is an option, you may considering this approach too

 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将被用来作为选择你的类型化厂

than ByIdTypedFactoryComponentSelector will be used as Selector for your Typed factory

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,

    ...

这篇关于我可以用类型化的工厂设备返回基于(枚举)参数实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆