Unity:具有多个构造函数的构造函数注入
我正在尝试使用 Unity 构造函数注入来注入 EF ObjectContext。 我的尝试是在引导程序中注册类型,如下所示:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<ObjectContext, MyObjectContext>(new InjectionConstructor());
}
EF 创建多个构造函数,如下所示
public MyObjectContext() : base("name=MyObjectContext", "MyObjectContext")
public MyObjectContext(string connectionString) : base(connectionString, "MyObjectContext")
public MyObjectContext(EntityConnection connection) : base(connection, "MyObjectContext")
在调试我的代码时,Unity 抛出一个 ResolutionFailedException 告诉我“MyObjectContext 类型有多个长度为 1 的构造函数。无法消除歧义。”当具有以下构造函数的新类被解析时。
public MainViewModel(UnityContainer container, MyObjectContext entities)
据我所知,使用 RegisterType
和 new InjectionConstructor()
作为参数可确保调用默认的无参数构造函数(这就是我想要的)。为什么 Unity 无法按预期解析类型?我错过了什么吗?
最好的问候
杰伊
I'm trying to inject an EF ObjectContext using Unity constructor injection.
My attemp is to register the type in the bootsprapper like this:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<ObjectContext, MyObjectContext>(new InjectionConstructor());
}
EF creates mutiple constructors which look like these
public MyObjectContext() : base("name=MyObjectContext", "MyObjectContext")
public MyObjectContext(string connectionString) : base(connectionString, "MyObjectContext")
public MyObjectContext(EntityConnection connection) : base(connection, "MyObjectContext")
When debugging my code Unity throws a ResolutionFailedException telling me "The type MyObjectContext has multiple constructors of length 1. Unable to disambiguate." at the time when a new class that has the following constructor is resolved.
public MainViewModel(UnityContainer container, MyObjectContext entities)
As far as I know using RegisterType
with new InjectionConstructor()
as argument ensures that the default parameterless constructor is called (thats what I want). Why can't Unity resolve the type as expected? Do I miss anything?
Best Regards
Jay
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的注册看起来正确。您确定正在调用注册码吗?尝试在其上放置断点。
(题外话:为什么要将容器传递给视图模型?)
Your registration looks right. You sure the registration code is getting called? Try putting a breakpoint on it.
(Off topic: why are you passing your container to your viewmodel?)