在ActionFilter中实施Unity MVC 5依赖项注入 [英] Implement Unity MVC 5 dependency injection in ActionFilter

查看:123
本文介绍了在ActionFilter中实施Unity MVC 5依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Unity(mvc5)在动作过滤器中插入此用户服务,但该服务为null。我该如何实现呢?

I'm trying to inject this user service via Unity (mvc5) in an actionfilter but it is null. How can I implement this?

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

    // other members
}


推荐答案

您必须先将 UnityFilterAttributeFilterProvider 注册为 FilterProvider

修改 App_Start > UnityMvcActivator 的Start方法,如下所示:

Modify the App_Start > UnityMvcActivator's Start method like this:

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

If you could not find the method. You probably installed wrong or out of date package. consider installing Install-Package Unity.Mvc on the package manager console.

这篇关于在ActionFilter中实施Unity MVC 5依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆