Unity注册非generics接口的generics类型
我的情景看起来(对我来说)很直接,但我找不到解决方案。
我有这种情况
public class Class : IInterface where T : class { }
接口不能通用(来自WCF lib。)
所以我想注册这样的界面
container.RegisterType(typeof (IInterface ), typeof (Class));
然后用T解决它
我该怎么做? 我错过了什么?
我的意图是做类似的事情
container.Resolve(/* specify T */);
如果您不需要使用不受控制的接口进行解析,则可以创建自己的受控接口,该接口使用generics并从不受控制的接口派生。 然后,您可以注册open generic并解析封闭的generics类型。
public interface IControlled : IUncontrolled {} public class Controlled : IControlled {} container.RegisterType(typeof(IControlled<>), typeof(Controlled<>)); IUncontrolled instance = container.Resolve>();
我错过了什么?
你错过了一家工厂。
想想看,没有神奇的妖精在背景上猜测你需要的类型。 你需要提供它。 通过明确说明配置时T
是这样的:
container.RegisterType( typeof(IInterface), typeof(Class));
或者通过创建一个在运行时传递T
的工厂:
public interface IInterfaceFactory { IInterface Create(); }
工厂可以注册如下:
container.RegisterInstance( new InterfaceFactory(container));
实现可以如下所示:
public class InterfaceFactory : IInterfaceFactory { private readonly IUnityContainer container; public InterfaceFactory(IUnityContainer container) { this.container = container; } public IInterface Create() { return this.container.Resolve>(); } }
现在,您可以将IInterfaceFactory
注入需要使用IInterface
消费者,他们可以通过调用Create
方法来请求所需的版本。
UPDATE
如果您认为代码太多,您还可以注册工厂代理,如下所示:
container.RegisterInstance>( type => container.Resolve( typeof(Class<>).MakeGenericType(type)));
这基本上是相同的,但现在在代表中内联。 您的消费者现在可以依赖于Func
而不是IInterfaceFactory
,并将类型实例传递给委托。
我个人更喜欢使用描述性界面,例如IInterfaceFactory
。 由你决定。