Reputation: 52952
I've come across some code that looks like this:
var something = this.container.Resolve<ICatManager>();
which in the web config has a mapping from ICatManager
to CatManager
.
However, CatManager has a constructor which takes 2 parameters, and no default constructor.
How does unity manage to create an instance of it?
Upvotes: 1
Views: 547
Reputation: 391456
Unity, and almost all other service container / service resolvers / service locators, work by analyzing the constructor(s) available, finding the "best one", then injecting parameters.
So, where does these parameters come from? From the service container itself.
For instance, if you have this service:
interface IService { ... }
class ServiceImplementation : IService
{
public ServiceImplementation(IOtherService os, IThirdService ts) { ... }
}
then when you resolve IService
Unity will try to also resolve IOtherService
and IThirdService
recursively. If the actual classes that implement those services also require other services, it does this resolution recursively until everything is OK.
So basically you could think of the resolution call like this:
var os = container.Resolve<IOtherService>();
var ts = container.Resolve<IThirdService>();
return new ServiceImplementation(os, ts);
Upvotes: 1