不知道这是否可行.
我需要根据枚举值返回正确的服务实现.所以手工编码的实现将如下所示:
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; } } }
返回的实现具有额外的依赖关系,需要通过容器注入,所以手工轧制的工厂将无法正常工作.
这是可能的,如果是,注册会是什么样子?
解决方法
如果将组件注册到容器中,将枚举值指定为组件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将用作您的Typed工厂的Selector
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,...