Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac with MVC 4 action filter property injection

I am using the Nuget MVC3 integration package for Autofac with MVC4. It mostly works (constructor injection with Controllers is working great) but it does not inject registered services into action filter properties.

This is my registration in Global.asax.cs:

builder.RegisterType<AspNetMembershipProviderWrapper>().As(typeof(IUserService)).InstancePerHttpRequest();
// 5) action filters
builder.RegisterType<SetCultureAttribute>().As<IActionFilter>().PropertiesAutowired().SingleInstance();
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Then in the SetCultureAttribute I have this:

public IUserService _userService { get; set; } // it doesn't get injected, null

Nor does this work in the constructor of the attribute:

_userService = DependencyResolver.Current.GetService<AspNetMembershipProviderWrapper>(); // always returns null

DependencyResolver.Current.GetService() also returns null for all other registered services when called within the action filter's constructor (I tried it out in the Debug windows to test it).

So I guess something is not working right. Is it ok to use MVC3 integration or should I use MVC4 Nuget package (which says it's for RC)?

Is there anything else I could try to make this work?

like image 500
mare Avatar asked Oct 14 '12 15:10

mare


1 Answers

In order to get ActionFilter injection working you need to register the provider, which I don't see in your example:

builder.RegisterFilterProvider();

There is doc on that here: http://code.google.com/p/autofac/wiki/MvcIntegration3

In either case, you registered the service as IUserService, so that's how you'd have to resolve it.

_userService = DependencyResolver.Current.GetService<IUserService>();

You don't need to register the attribute. Check the wiki link above for more.

like image 180
Travis Illig Avatar answered Nov 12 '22 12:11

Travis Illig