Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Framework IoC with default constructor

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>();
}

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...

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?

like image 490
Rod Johnson Avatar asked Sep 15 '10 02:09

Rod Johnson


1 Answers

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.

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.

Your choices are:

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

Using the API:

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

Using XML config:

<container>
  <register type="UserService">
    <constructor />
  </register>
</container>
like image 192
Chris Tavares Avatar answered Oct 01 '22 10:10

Chris Tavares