具有依赖注入的过滤器和FilterProvider;管理每个请求?

时间:2017-08-12 17:11:35

标签: c# .net asp.net-web-api dependency-injection unity-container

我一直在尝试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呆在一起,有没有更好的解决方案?

1 个答案:

答案 0 :(得分:1)

在WebApi框架中缓存了缓存。因此它们是singletons并在请求之间重复使用。您CustomAuthorizeFilter的实例在申请有效期内永远不会被处置,并且会引用IFakeService