We recently switched from ninject to Simple Injector because ninject is really slow. I'm running into a serious problem when trying to inject Web Api ActionFilter properties during runtime. No matter what I have tried they are not resolved. I'm basing the code on the following docs here and here and here. Please note that I've also tried registering my own IFilterProvider..
I'm creating my container like this:
var container = new Container();
container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior();
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
My attribute
public class InjectAttribute : Attribute { }
IPropertySelectionBehavior implementation
public class InjectAttributePropertySelectionBehavior : IPropertySelectionBehavior {
public bool SelectProperty(Type serviceType, PropertyInfo property) {
return property.GetCustomAttributes(typeof(InjectAttribute), true).Any();
}
}
Sample code that I'm trying inject.
public class MyActionFilterAttribute : ActionFilterAttribute {
[Inject]
public IMyRepository MyRepository { get; set; }
}
Has anyone else been able to inject properties on Web Api ActionFilters?
I just tried to reproduce your issue by building a sample Web API project with the code in the articles you referenced, but it worked directly.
What I did was the following:
SimpleInjectorWebApiDependencyResolver
from here and registered (just as in your question).SimpleInjectorActionFilterProvider
from here and registered it as shown just below the code snippet in that article.InjectAttributePropertySelectionBehavior
and registered it like in your example.InjectAttribute
.MyActionFilterAttribute
(and overwrite the OnActionExecuting
method to be able to set a break point).IMyRepository
and a MyRepositoryImpl
class.MyRepositoryImpl
by its interface in the container.MyActionFilterAttribute
.After doing this and running the application by calling the action, I see visual studio breaking inside the OnActionExecuting method with the MyRepository
property being set.
This is my configuration:
var container = new Container();
container.Options.PropertySelectionBehavior =
new InjectAttributePropertySelectionBehavior();
container.Register<IMyRepository, MyRepositoryImpl>();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.Services.Remove(typeof(IFilterProvider),
GlobalConfiguration.Configuration.Services.GetFilterProviders()
.OfType<ActionDescriptorFilterProvider>().Single());
GlobalConfiguration.Configuration.Services.Add(
typeof(IFilterProvider),
new SimpleInjectorActionFilterProvider(container));