统一框架IoC和默认的构造函数 [英] Unity Framework IoC with default constructor

查看:350
本文介绍了统一框架IoC和默认的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想注入依赖我的MVC控制器这样

I'm trying to inject a dependency to my MVC controllers like this

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

将UserService类有这样的构造......

The UserService class has a constructor like this...

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 exception I am getting is the following...

当前类型,
  Repositories.IUserRepository,
  是一个接口,并且不能
  建。是否缺少类型
  映射?

The current type, Repositories.IUserRepository, is an interface and cannot be constructed. Are you missing a type mapping?

它看起来像它试图注入构造到服务,但是默认的就足够了?为什么不映射到参数的构造函数?

It looks like it's trying to inject a constructor into the service, but the default would suffice? Why is it not mapping to the parameterless constructor?

推荐答案

的统一默认约定(这是pretty的文件中明确规定)是选择最参数的构造。你不能只是做一个毯子声明说:这不是真的,国际奥委会将找到最具体的构造函数,如果不指定构造函数的参数,而注册一个类型,它会自动调用默认的构造函数。每个容器的实施能够而且确实有不同的默认值。

The Unity default convention (which is pretty clearly spelled out in the documentation) is to choose the constructor with the most parameters. You can't just make a blanket statement that "it's not true that IoC will find the most specific constructor , if you don't specify the constructor parameters while registering a type , it will automatically call default constructor." Each container implementation can and does have different defaults.

在Unity的情况下,就像我说的,它会选择最参数的构造。如果有两个拥有最参数,那么这将是含糊不清,并抛出。如果你想要的东西不同,你必须配置容器做到这一点。

In Unity's case, like I said, it will choose the constructor with the most parameters. If there are two that have the most parameters, then it'll be ambiguous and throw. If you want something different, you must configure the container to do that.

您的选择是:

放在你想叫构造[InjectionConstructor]属性(不推荐,但快速和容易)。

Put the [InjectionConstructor] attribute on the constructor you want called (not recommended, but quick and easy).

使用API​​:

container.RegisterType<UserService>(new InjectionConstructor());  

使用XML配置:

Using XML config:

<container>
  <register type="UserService">
    <constructor />
  </register>
</container>

这篇关于统一框架IoC和默认的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆