当我尝试在属性上调用DependencyResolver时返回null,我在项目中使用Unity.WebAPI。 这是我的代码:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MSIAuthorizeAttribute : AuthorizationFilterAttribute
{
private bool _perUser;
private ISecurityService _securityService;
/// <summary>
/// constractor for MSIAuthorizeAttribute
/// </summary>
public MSIAuthorizeAttribute(bool perUser = true)
{
_perUser = perUser;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
var persistenceService = DependencyResolver.Current.GetService<IPersistenceService>();
var logService = DependencyResolver.Current.GetService<ILogService>();
var vbUtilities = DependencyResolver.Current.GetService<IVBUtilities>();
_securityService = new SecurityService(persistenceService,logService,vbUtilities);
...
}
}
答案 0 :(得分:1)
致Janki
我找到了答案,您需要在定义依赖注入容器的位置注册过滤器。这是一个例子:
public static void RegisterFilterProviders(HttpConfiguration config)
{
var providers = config.Services.GetFilterProviders().ToList();
config.Services.Add(typeof(IFilterProvider), new UnityActionFilterProvider(GetConfiguredContainer()));
var defaultprovider = providers.First(p => p is ActionDescriptorFilterProvider);
config.Services.Remove(typeof(IFilterProvider), defaultprovider);
}
然后在WebApiConfig.cs
中添加以下代码行:
UnityConfig.RegisterFilterProviders(config);
答案 1 :(得分:0)
我找到了解决方案:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MSIAuthorizeAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
private bool _perUser;
private ISecurityService _securityService;
[Dependency]
public ILogService LogService { get; set; }
[Dependency]
public IVBUtilities VbUtilities { get; set; }
[Dependency]
public IPersistenceService PersistenceService { get; set; }
/// <summary>
/// constractor for MSIAuthorizeAttribute
/// </summary>
public MSIAuthorizeAttribute( bool perUser = true)
{
_perUser = perUser;
}
public override void OnActionExecuted(HttpActionExecutedContext actionContext)
{...}