Rectangle 27 0

asp.net mvc Use named registration in autofac with MVC controller injection integration?


builder.RegisterType<ComplexController>().WithParameters(new [] {
 new ResolvedParameter((p,c) => p.Name == "bar",(p,c) => c.ResolveNamed<IFoo>("bar")),
 new ResolvedParameter((p,c) => p.Name == "baz",(p,c) => c.ResolveNamed<IFoo>("baz"))
});

public class ComplexController: Controller
{
    public ComplexController(IFoo baz, IFoo bar)
    {
         //...
    }
}
builder.RegisterType<SomeController>()
       .WithParameter(ResolvedParameter.ForNamed<IFoo>("bar"));
builder.RegisterType<OtherController>()
       .WithParameter(ResolvedParameter.ForNamed<IFoo>("baz"));

If a controller needs multiple IFoo you can specify the resolve parameter e.g. with name (with a little bit extra syntax, but you can hide it behind an extension method):

Thanks, that works. Occasionally a controller will need more than one IFoo - can I specify which parameter name goes to which named implementation?

You can register (actually re-register if you are using builder.RegisterControllers()) your controllers with the parameter which will be used during resolve:

Note