Can I Use Typed Factory Facility to Return Implementation Based on (enum) Parameter?

会有一股神秘感。 提交于 2019-12-20 18:32:28

问题


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?


回答1:


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

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,

    ...



回答2:


It looks like this is possible. Take a look at this:

Example

You will need to create an ITypedFactoryComponentSelector implementation to resolve the call, and register it in the container to only resolve the calls for the classes you are interested in.



来源:https://stackoverflow.com/questions/12711840/can-i-use-typed-factory-facility-to-return-implementation-based-on-enum-parame

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