user786
user786

Reputation: 4364

sample example about Dependency injection needs explanation

I was going through this article about dependency injection http://www.asp.net/web-api/overview/advanced/dependency-injection

It shows Unity Container from Microsoft.

There are a few things that are not making sense to me

for example, following line

  public ProductsController(IProductRepository repository)

The above is the constructor of Controller. I need to know who passes the repository to the constructor? ANd is that made possible by registering IProductRepository interface with Unity?

  public static void Register(HttpConfiguration config)
 {
    var container = new UnityContainer();
    container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

// Other Web API configuration not shown.
}

Is the above code is all needed to make MVC pass the object to the constructor of a controller?

Upvotes: 0

Views: 52

Answers (1)

Zein Makki
Zein Makki

Reputation: 30032

You answered your own question:

is that made possible by registering IProductRepository interface with Unity?

Yes.

When you request to resolve a type using Unity, the container searches for public constructors. If the constructor needs some implementation (IProductRepository in your case), the container searches within its registrations for an implementation for all the needed parameters. If found, it resolves that. This is a recursive process.

So yes. You need to register an implementation of IProductRepository using the container in order to resolve an instance of the Controller using that container.

Upvotes: 3

Related Questions