2016-01-13 47 views
1

比方说,我有一个类取决于接口IFace以及注入构造函数的其他几个依赖项(由...描述)。我也有2个实现的接口IFace在UnityContainer中注册类型以使用其他命名注册来解析构造函数参数

class Impl1 : IFace {} 
class Impl2 : IFace {} 

class Std : IStd { 
    Std(IFace impl1, IOtherDependency otherDep, ...) { ... } 
} 

我要注册Impl1作为默认的实现和注册Impl2为名为执行其应注入某些类。

container.RegisterType<IFace, Impl1>(); 
container.RegisterType<IFace, Impl2>("impl2"); 

注册Std这样会注入默认Impl1实现:

container.RegisterType<IStd, Std>(); // this would inject the default implementation Impl1 

如何注册Std有一个名为注射执行不诉诸手动调用Resolve()?我能想出的最好的是这样的:

container.RegisterType<IStd, Std>(
    new InjectionConstructor(new ResolvedParameter<IFace>("impl2"), typeof(IOtherDependency, ...))); 

我不与上面的方法一样的是,我还需要指定其他所有构造函数的参数;当签名发生变化时,我需要调整注册,编译器不会提出问题(运行时异常被抛出),而智能感知在此处不起作用。

我想吃点什么是沿着线的东西:(该InjectNamedType显然是由)

container.RegisterType<IStd, Std>(
    InjectNamedType<IFace>(name: "impl2")); // this would tell Unity to look for registration of IFace with that name 

回答

1

这里是你如何能做到这一点:

container.RegisterType<IStd>(
    new InjectionFactory(x => 
     x.Resolve<Std>(new DependencyOverride<IFace>(x.Resolve<IFace>("impl2"))))); 

InjectionFactory让你指定创建IStd对象的工厂逻辑。我们使用Resolve方法来解析具体的Std类,我们使用DependencyOverride类来指定要使用哪个实现IFace。我们再次使用Resolve方法来解决特定的实现。

请注意,只有当有人试图解决IStd(或类别取决于IStd)而不是当您注册IStd时,工厂逻辑才会运行。

+0

正是我所需要的。谢谢! – Martin

相关问题