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?
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).
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?
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