我一直在尝试Unity和客户Filter
/ FilterProvider
。我担心的是这些课程从未被处理过。这是我开始的代码示例:
//FilterProvider
public class CustomFilterProvider: IFilterProvider
{
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
if (actionDescriptor.GetCustomAttributes<CustomAuthorizeAttribute>().Any())
{
var filter = UnityinstanceLocator.GetConfiguredContainer().Resolve<CustomAuthorize>();
yield return new FilterInfo(filter, FilterScope.Global);
}
}
}
//Filter
public class CustomAuthorizeFilter: IAuthorizationFilter
{
private readonly IFakeService _fakeService;
public CustomAuthorizeFilter(IFakeService fakeService)
{
_fakeService = fakeService;
}
public bool AllowMultiple { get; }
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
...Do Some stuff
}
}
//Attribute
public class CustomAuthorizeAttribute : Attribute
{
}
我的IFakeService
实施IDisposable
。我把它设置为测试。我IFakeService
的统一注册使用了HierarchicalLifetimeManager
。当它在过滤器内部时,我从未看到它被丢弃。将IFakeService
注入控制器可以按预期工作。
过滤器提供程序的启动看起来像这样(我正在使用OWIN):
var config = new HttpConfiguration {DependencyResolver = new UnityDependencyResolver(UnityinstanceLocator.GetConfiguredContainer())};
config.Services.Add(typeof(IFilterProvider), new ComceptFilterProvider());
我想我可以去学校并将我的一次性类包装在using
语句中的ExecuteAuthorizationFilterAsync
语句中,并避免依赖注入。如果我和Unity呆在一起,有没有更好的解决方案?
答案 0 :(得分:1)
在WebApi框架中缓存了缓存。因此它们是singletons并在请求之间重复使用。您CustomAuthorizeFilter
的实例在申请有效期内永远不会被处置,并且会引用IFakeService
。