我正在尝试通过Unity(mvc5)在actionfilter中注入此用户服务,但它为null。我该如何实现呢?
public class TestFilter : ActionFilterAttribute
{
// this is always null
[Dependency]
public IUserService UserService { get; set; }
// other members
}
答案 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
。