Unity Framework IoC使用默认构造函数

Rod*_*son 9 c# asp.net-mvc ioc-container unity-container

我正试图像这样向我的MVC控制器注入一个依赖项

private static void RegisterContainer(IUnityContainer container)
{            
    container
        .RegisterType<IUserService, UserService>()
        .RegisterType<IFacebookService, FacebookService>();
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的例外是以下......

当前类型Repositories.IUserRepository是一个接口,无法构造.你错过了类型映射吗?

看起来它正在尝试将一个构造函数注入到服务中,但是默认就足够了吗?为什么它不映射到无参数构造函数?

Chr*_*res 25

Unity默认约定(在文档中非常清楚地说明)是选择具有最多参数的构造函数.你不能只是做一个简单的声明,"IoC找不到最具体的构造函数是不正确的,如果在注册类型时没有指定构造函数参数,它将自动调用默认构造函数." 每个容器实现可以并且确实具有不同的默认值.

在Unity的情况下,就像我说的那样,它会选择参数最多的构造函数.如果有两个具有最多参数,那么它将是模棱两可的并抛出.如果您想要不同的东西,则必须配置容器来执行此操作.

你的选择是:

将[InjectionConstructor]属性放在要调用的构造函数上(不推荐,但快速简便).

使用API​​:

container.RegisterType<UserService>(new InjectionConstructor());  
Run Code Online (Sandbox Code Playgroud)

使用XML配置:

<container>
  <register type="UserService">
    <constructor />
  </register>
</container>
Run Code Online (Sandbox Code Playgroud)