我试图像这样注入一个依赖关系到我的MVC控制器
private static void RegisterContainer(IUnityContainer container) { container .RegisterType<IUserService,UserService>() .RegisterType<IFacebookService,FacebookService>(); }
UserService类有一个这样的构造函数…
public UserService(): this(new UserRepository(),new FacebookService()) { //this a parameterless constructor... why doesnt it get picked up by unity? } public UserService(IUserRepository repository,IFacebookService facebook_service) { Repository=repository; this.FacebookService=facebook_service; }
我得到的例外是以下…
The current type,
Repositories.IUserRepository,
is an interface and cannot be
constructed. Are you missing a type
mapping?
看起来它正在尝试将一个构造函数注入到服务中,但默认值就足够了为什么不映射到无参数的构造函数?
解决方法
Unity默认约定(在文档中很清楚地列出)是选择具有最多参数的构造函数.您不能只是做一个全面的陈述,“IoC将找到最具体的构造函数不是真的,如果在注册类型时没有指定构造函数参数,它将自动调用默认构造函数.每个容器实现可以并且确实具有不同的默认值.
在Unity的情况下,就像我说的那样,它将选择具有最多参数的构造函数.如果有两个参数最多,那么它会变得模糊和抛出.如果你想要不同的东西,你必须配置容器来做到这一点.
你的选择是:
将[InjectionConstructor]属性放在你想要调用的构造函数上(不推荐,但是简单快捷).
使用API:
container.RegisterType<UserService>(new InjectionConstructor());
使用XML配置:
<container> <register type="UserService"> <constructor /> </register> </container>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。