在ActionFilter中实现Unity MVC 5依赖注入

时间:2015-08-03 11:57:59

标签: asp.net-mvc-5 unity-container actionfilterattribute

我正在尝试通过Unity(mvc5)在actionfilter中注入此用户服务,但它为null。我该如何实现呢?

public class TestFilter : ActionFilterAttribute
{
    // this is always null
    [Dependency]
    public IUserService UserService { get; set; }

    // other members
}

1 个答案:

答案 0 :(得分:1)

您必须先将UnityFilterAttributeFilterProvider注册为FilterProvider

修改App_Start> UnityMvcActivator这样的Start方法:

public static void Start()
{
    var container = UnityConfig.GetConfiguredContainer();

    FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
    FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

    Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}

如果找不到方法。您可能安装了错误或过时的软件包。考虑在包管理器控制台上安装Install-Package Unity.Mvc