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!
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>()
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