23

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?

Richard Garside
  • 87,839
  • 11
  • 80
  • 93

2 Answers2

33

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?

Community
  • 1
  • 1
Richard Garside
  • 87,839
  • 11
  • 80
  • 93
  • 3
    You should't do that. It's a bad practice. Instead of service locator approach it's better to do constructor injection. Simply inject IService to the constructor and use the injected instace as a class fiel – Wojteq Oct 20 '11 at 15:19
  • 1
    How can I use named parameters with that approach? – Richard Garside Oct 20 '11 at 15:23
  • 2
    You can get something similar using Factory delegate: http://code.google.com/p/autofac/wiki/DelegateFactories – Wojteq Oct 20 '11 at 15:25
11
AutofacDependencyResolver.Current.ApplicationContainer

.Resolve

.ResolveNamed

.ResolveKeyed

.....
chown
  • 51,908
  • 16
  • 134
  • 170
chenZ
  • 920
  • 4
  • 16