Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the autofac container in ASP.NET MVC3 controller?

Tags:

I would like to resolve a dependency using a named parameter in an MVC controller. If I can access the Autofac container I should be able to do it like so:

var service = Container.Resolve<IService>(     new NamedParameter("fileExtension", dupExt) ); 

I can't find out how to access the AutoFac container. Is there a global reference to the container that I can use or is there another way to use named parameters?

like image 327
Richard Garside Avatar asked Oct 20 '11 15:10

Richard Garside


People also ask

How do I get Autofac containers?

From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).


1 Answers

I've just discovered I can use IComponentContext for the same thing. You can inject an instance of IComponentContext into the controller.

public class MyController : Controller {     private readonly IComponentContext _icoContext;      public void MyController(IComponentContext icoContext)     {         _icoContext= icoContext;     }      public ActionResult Index()     {         var service = _icoContext.Resolve<IService>(             new NamedParameter("ext", "txt")         );     } } 

I've found some good advice on getting global access to the container in this question: Autofac in web applications, where should I store the container for easy access?

I've also found how to get access to the dependency resolver globally here: Global access to autofac dependency resolver in ASP.NET MVC3?

like image 167
Richard Garside Avatar answered Oct 21 '22 17:10

Richard Garside