Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve instance with Autofac and Asp.Net MVC

I have just started to try out Autofac and I think I am confusing myself with resolving the concrete classes.

I have managed to register my Interfaces to my Concrete classes as below

builder.RegisterType<TestClass>().As<ITest>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

This builds fine. The problem I am having is how to do get an instance of this in my mvc controller? Most things I have read say I need to create a new instance of ContainerBuilder and then call the scope.Resolve method, but surely this is bad practice and shouldnt be needed in each controller?

I think the confusion is when and how to access 'Container' so that I can call the resolve method as and when I need to.

Im a newbie at this as you have probably guessed!

like image 248
Raj Avatar asked Oct 17 '14 12:10

Raj


1 Answers

One way to do it is use the controllers constructor as Autofac will handle this for you:

public class MyController : Controller
{
    private ITest _test;

    public MyController(ITest test)
    {
        _test = test;
    }
}

If you don't want to use the constructor and let the dependency get injected for you, you can do this in your controller action method:

var test = DependencyResolver.Current.GetService<ITest>()
like image 117
DavidG Avatar answered Nov 15 '22 08:11

DavidG