【发布时间】:2015-08-05 07:49:33
【问题描述】:
我有一个 Web API 2 项目,它正在实现一个自定义 IAuthenticationFilter,如下所示。
我的问题是 Unity 没有在 BasicAuthenticator 类中注入 UnitOfWork。正如预期的那样,Unity 成功地将 UnitOfWork 注入到控制器中。
public class BasicAuthenticator : Attribute, IAuthenticationFilter
{
[Dependency]
public UnitOfWork UoW { get; set; }
public bool AllowMultiple { get { return false; } }
public Task AuthenticateAsync(HttpAuthenticationContext context,
CancellationToken cancellationToken)
{
// ignore missing implementation
context.Principal = new ClaimsPrincipal(new[] { id });
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
CancellationToken cancellationToken) {}
}
【问题讨论】:
-
由于 BasicAuthenticatior 是一个 Attribute 并且可能被这样使用,所以不会有 DependencyInjection,因为它不会由 unity 而是由 mvc 框架实例化。您可以尝试在 BasicAuthetnicator 构造函数中获取统一容器。
-
@TGlatzer,你是对的,框架实例化了过滤器。但是,您可以创建一个自定义过滤器提供程序,它将对过滤器执行依赖注入。
标签: c# entity-framework unity-container asp.net-web-api2 unit-of-work