Ninject:将属性注入ActionFilterAttribute

时间:2016-03-22 14:24:01

标签: c# asp.net-web-api ninject

我想在Ninject的ActionFilterAttribute中实现DI。我发现this manual(实际上我今天已经阅读了数十篇文章),但它适用于Unity。我在Ninject上实现它的尝试在这里:

public class MyFilter : ActionFilterAttribute
{
    [Inject]
    public IDepend Depend { get; set; }
    // another code
}

绑定:

public class NinjectResolver : IDependencyResolver
{
    // another code
    private IKernel AddRequestBindings(IKernel kernel)
    {
        // another code
        kernel.Bind<IDepend>().To<Depend>();
        return kernel;
    }
}

自定义FilterProvider:

public class WebApiNinjectActionFilterProvider : ActionDescriptorFilterProvider, IFilterProvider
{
    private readonly IKernel _kernel;
    private readonly IEnumerable<IFilterProvider> _filterProviders;

    public WebApiNinjectActionFilterProvider(IKernel kernel, IEnumerable<IFilterProvider> filterProviders)
    {
        _kernel = kernel;
        _filterProviders = filterProviders;
    }

    public new IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
    {
        var filters = _filterProviders.SelectMany(fp => fp.GetFilters(configuration, actionDescriptor)).ToList();
        foreach (var filter in filters)
        {
            // GET ActivationException HERE!!!!!
            _kernel.Inject(filter.Instance);
        }
        return filters;
    }

    public static void RegisterFilterProviders(IKernel ninjectKernel)
    {
        var providers = GlobalConfiguration.Configuration.Services.GetFilterProviders().ToList();
        GlobalConfiguration.Configuration.Services.Add(typeof(IFilterProvider),
                                                       new WebApiNinjectActionFilterProvider(ninjectKernel, providers));
        var defaultprovider = providers.First(i => i is ActionDescriptorFilterProvider);
        GlobalConfiguration.Configuration.Services.Remove(typeof(IFilterProvider), defaultprovider);
    }
}
从WebApiConfig调用

    public static void Register(HttpConfiguration config)
    {
        var ninjectKernel = new StandardKernel();
        config.DependencyResolver = new NinjectResolver(ninjectKernel);

        WebApiNinjectActionFilterProvider.RegisterFilterProviders(ninjectKernel);
    }

最后采取行动:

    [MyFilter]
    public async Task<string> Test()
    {
        return "Hello world";
    }

问题是我在这一行得到了ActivationException:

_kernel.Inject(filter.Instance);

ActivationException&#39; s激活路径:

2)将依赖IDepend注入属性Depend of MyFilter

1)请求MyFilter

如果要向控制器注入相同的属性 - 它会注入罚款。任何想法如何改进我的代码?

1 个答案:

答案 0 :(得分:0)

我是以错误的方式做IActionFilter DI。我在this blogpost of Mark Seemann找到了正确的方法。

DI via Ninject以这种方式实施:

var myFilter = new MyFilter(ninjectKernel.Get<IDepend>());
config.Filters.Add(myFilter);