I am trying to use Autofac and Autofac.Integrations.Web to register ASP.NET MVC controllers. I am currently using assembly scanni开发者_如何学Cng to find the controllers but one of them needs a special parameter that I would prefer to pass in instead. Found below are the registrations I have tried.
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// so far I have tried
builder.Register<SpecialController>(c =>
new SpecialController(wierdParam, c.Resolve<IDependency>())
).Named<SpecialController>("controller.special")
.As<SpecialController>().As<IController>();
/* And this
builder.Register<SpecialController>(c =>
new SpecialController(url, c.Resolve<IDependency>())
);
*/
/* plus this
builder.Register<SpecialController>(c =>
new SpecialController(url, c.Resolve<IDependency>())
).Named<SpecialController>("controller.special");
*/
Thank you for your help.
I was able to find a registration that worked after some tinkering and mucking with the debugger.
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register<IController>(c =>
new SpecialController(weirdParam, c.Resolve<IDependency>())
).Named<IController>("controller.special");
This works because Autofac automatically registers different controllers as hidden named registrations of the type IController
.
try to use withParameter if u want to pass any class object
E.g:
builder.RegisterType<ApplicationSettingsRepository>().As<IApplicationSettingsRepository>()
.WithParameter(new TypedParameter(typeof(NameValueCollection), ConfigurationManager.AppSettings))
精彩评论