Richard Garside
Richard Garside

Reputation: 89140

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

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?

Upvotes: 23

Views: 18973

Answers (2)

Richard Garside
Richard Garside

Reputation: 89140

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?

Upvotes: 33

chenZ
chenZ

Reputation: 930

AutofacDependencyResolver.Current.ApplicationContainer

.Resolve

.ResolveNamed

.ResolveKeyed

.....

Upvotes: 12

Related Questions