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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With