Jeffrey Kern Jeffrey Kern - 1 year ago 178
ASP.NET (C#) Question

Autofac + MVC5: Resolving a Service's Dependencies

I've gotten the basics done with resolving controller dependencies with Autofac + MVC5. However, I'm wondering how to inject dependencies into services.

Given a sample definition as such, how can I create/get an instantiated copy of the class with Autofac resolving the necessary dependencies?

Bar : IBar

Public Bar(IFoo foo, IPanda panda)



Answer Source

Ultimately it just comes down to registering the type in the Container. Such as:

var builder = new ContainerBuilder();
var container = builder.Build();

I'm assuming you have similar code using the Builder somewhere during your initialization.

There are several different ways to register and configure dependencies, lifetimes, interceptors etc, more info here:

Once everything is registered, whenever Autofac tries to instantiate your controller, it'll inspect your controller's constructor, and when it finds an IBar as dependency, it'll look for it's container registration and instantiate accordingly.

The same applies when it tries to instantiate IBar, it'll notice IFoo and IPanda and repeat the same process.

The main difference is that Autofac supports automatic registration of your controllers, just to spare you the hassle of registering each one manually.

So in the end, it'll all be chained in that manner, dependencies created as needed. I tend to avoid using ServiceLocator style of instantiation by requesting a dependency directly, and just let Autofac provide the dependencies during construction.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download