我可以使用类型工厂设备返回基于(枚举)参数的实现吗?
不确定这是否可行。
我需要根据枚举值返回正确的服务实现。 所以手工编码的实现看起来像:
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(); container.Register ( Component.For(), Component.For().ImplementedBy().Named(YourEnum.Option1.ToString()), Component.For() .AsFactory(x => x.SelectedWith()) .LifeStyle.Singleton, ...
看起来这是可能的。 看看这个:
例
您需要创建一个ITypedFactoryComponentSelector实现来解析调用,并在容器中注册它以仅解析您感兴趣的类的调用。
- 使用www-form-urlencoded发送时,为什么我的JSON字符串在服务器端为null?
- entity framework4.1两个具有相同属性名称的表
- SmtpClient:连接尝试失败,因为连接方在一段时间后没有正确响应
- 在entity framework中将ObjectResult与输入参数一起使用到StoredProcedure的正确方法是什么? (输出映射到复杂类型属性)
- 等待最后一个方法行
- .NET线程 – HttpWebRequest BeginGetResponse + AutoResetEvent
- C#ICMPv6校验和计算
- 关于结构的问题
- 将日期格式从dd / MM / yyyy更改为MM / dd / yyyy