可以从 ASP.NET 核心项目中的简单注入器注入 IAsyncActionFilter 吗?

Possible to inject into IAsyncActionFilter from Simple Injector in ASP.NET Core project?

考虑一个 ASP.NET 核心 MVC 项目中的一个简单的动作过滤器,它需要一个依赖项:

public class TestActionFilter : IAsyncActionFilter {
    private readonly IMyDependency _dep;

    public class TestActionFilter(IMyDependency dep)
    {
        _dep = dep;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context,
                                             ActionExecutionDelegate next)
    {
        // do things with _dep...
        await next();
    }
}

我已经 IMyDependency 在 Simple Injector 注册并在其他地方工作。我希望 Simple Injector 也能处理动作过滤器。

如果我为同一类型添加 IServiceCollection 注册,它会被注入到操作过滤器中。虽然我不想要两个绑定,但我试图避免使用框架容器并坚持使用 Simple Injector。

是否有一些技巧可以让 Simple Injector 处理我的动作过滤器?我记得在旧的 Simple Injector 化身中曾经有某种 "filter provider" 概念允许这样做。

此时,ASP.NET 核心 MVC 的简单注入器集成包中没有任何东西可以简化过滤器属性的使用。我们还是hoping that Microsoft will add simplifications to the framework to support non-conformers (since Microsoft promised to make integration as smooth as it can be), but this seems a lost cause.

有几个解决方案。一种方法是交叉布线,就像您已经做过的那样。但是你交叉的越多,你越是将控制从 Simple Injector 移出,你就越失去 Simple Injector 提供的验证能力。当您的所有对象图都是 singletons 时,这通常不会有太大问题,但这是一个不同的讨论。

另一种选择是在内置配置系统中创建代理过滤器,委托给从 Simple Injector 解析的真实过滤器。这样的代理可以定义如下:

public sealed class SimpleInjectiorAsyncActionFilterProxy<TAsyncActionFilter>
    : IAsyncActionFilter
    where TAsyncActionFilter : class, IAsyncActionFilter {
    private readonly Container container;
    public SimpleInjectiorAsyncActionFilterProxy(Container container) {
        this.container = container; 
    }

    public Task OnActionExecutionAsync(
        ActionExecutingContext c, ActionExecutionDelegate n) =>
        container.GetInstance<TAsyncActionFilter>().OnActionExecutionAsync(c, n);
}

这是使用此代理连接过滤器的方式:

container.Register<TestActionFilter>();

services.AddMvc(options =>
{
    options.Filters.Add(
        new SimpleInjectiorAsyncActionFilterProxy<TestActionFilter>(container));
});

这对全局过滤器非常有用。当谈到控制器或动作范围过滤器时,请查看 passive attributes.