![](/img/trans.png)
[英]Unity (dependency injection): How to pass in a parameter to the constructor in RegisterType
[英]How to resolve dependency by using a named registertype in Unity?
public interface IFoo {}
public interface IBar {}
public class Foo1 : IFoo {}
public class FooOne : IFoo {}
public class FooTwo : IFoo {}
public class BarOne : IBar
{
public BarOne(IFoo foo) {}
}
public class BarTwo : IBar
{
public BarTwo(IFoo foo) {}
}
class Program
{
static void Main(string[] args)
{
UnityContainer container = new UnityContainer();
container.RegisterType<IFoo, FooOne>("One")
.RegisterType<IFoo, FooTwo>("Two")
.RegisterType<IBar, BarOne>("One")
.RegisterType<IFoo, BarTwo>("Two");
string fooType = "One";
string barType = "Two";
IFoo myFoo = container.Resolve<IFoo>(fooType);
IBar myBar = container.Resolve<IBar>(barType);
}
}
上面的代码示例抛出此错误:
解决依赖关系失败,键入=“ ConsoleApplication5.IBar”,名称=“ Two”。 发生以下异常:正在解决。 异常是:InvalidOperationException-当前类型ConsoleApplication5.IFoo是一个接口,无法构造。 您是否缺少类型映射? - - - - - - - - - - - - - - - - - - - - - - - - 当时例外情况是,该容器是:
解决ConsoleApplication5.BarTwo,Two(从ConsoleApplication5.IBar映射,两个)解决构造函数ConsoleApplication5.BarTwo(ConsoleApplication5.IFoo foo)的参数“ foo”解决ConsoleApplication5.IFoo,(无)
我的解决方案是使用DependencyResolver
更改此行:
IBar myBar = container.Resolve<IBar>(barType);
对此:
IBar myBar = container.Resolve<IBar>(barType, new DependencyOverride<IFoo>(myFoo));
我想使用RegisterType
方法解决此问题。 有可能还是有其他解决方案?
谢谢。
您必须确定在解析IBar时应使用哪个IFoo 命名注册单位。
container.RegisterType<IFoo, FooOne>("One")
.RegisterType<IFoo, FooTwo>("Two")
.RegisterType<IBar, BarOne>("One", new InjectionConstructor(
new ResolvedParameter<IFoo>("One")))
.RegisterType<IBar, BarTwo>("Two", new InjectionConstructor(
new ResolvedParameter<IFoo>("Two")));
问题是IFoo被不同的实现两次注册,而unito不知道在解析该类型时应使用哪个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.