Simple Injector property injection on action filter

╄→гoц情女王★ 提交于 2019-11-29 02:24:37

You are registering an initializer on your UserAuthorisation attribute. Initializers however, are only used by the container when a type is created by the container itself. Since attributes are created by the CLR, the initializer won't go off.

The SimpleInjector.Integration.Web.Mvc.dll (this NuGet package) contains a RegisterMvcAttributeFilterProvider extension method. This will register an AttributeFilterProvider that will do implicit property injection (and call into the container.InjectProperties method). After calling container.RegisterMvcAttributeFilterProvider(), you will see that this property is injected automatically.

I have selected Stevens answer as the answer as it got me to a solution and I am now using the command handler that he mentioned in the comments.

I have put a simple work around in to get my global filters injected.

In the App_Start\SimpleInjectorInitializer.cs I have added RegisterGlobalFilters like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
{
    //Add simple injector resolved types.
    filters.Add(container.GetInstance<UserAuthorisation>());
}

And in the Initialize method I have added this RegisterGlobalFilters(GlobalFilters.Filters, container);

The complete method looks like this:

/// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
public static void Initialize()
{
    var container = new Container();
    InitializeContainer(container);
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
    container.RegisterMvcAttributeFilterProvider();
    container.Verify();
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

    RegisterGlobalFilters(GlobalFilters.Filters, container);
}

As I said very simple. Just get my instances from simple injector and then add them to the global list, I am sure there are better ways to do this.

This way does mean you do not need to change the global.asax.cs which is possibly a good thing.

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