Autofac - Inject properties into a asp.net mvc controller

笑着哭i 提交于 2019-12-05 12:28:38

This should work:

builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();

Some more info on the autofac website: http://code.google.com/p/autofac/wiki/PropertyInjection

You may want to consider using an Autofac Aggregate Service:

An aggregate service is useful when you need to treat a set of dependencies as one dependency. When a class depends on several constructor-injected services, or have several property-injected services, moving those services into a separate class yields a simpler API.

An example is super- and subclasses where the superclass have one or more constructor-injected dependencies. The subclasses must usually inherit these dependencies, even though they might only be useful to the superclass. With an aggregate service, the superclass constructor parameters can be collapsed into one parameter, reducing the repetitiveness in subclasses. Another important side effect is that subclasses are now insulated against changes in the superclass dependencies, introducing a new dependency in the superclass means only changing the aggregate service definition.

This works for me:

using Autofac;
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;    

builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker();

nickvane's answer is correct. Just make sure

builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();

is after your all dependencies are registered. Or in other words, just right before you build your container.

So final code will look like

.
.
.
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();           

var container = builder.Build();

Need to call also for MVC:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

For Web API:

HttpConfiguration config = GlobalConfiguration.Configuration;
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!