ConsoleAppFramework icon indicating copy to clipboard operation
ConsoleAppFramework copied to clipboard

Global filters with dependency injection

Open wozzo opened this issue 3 years ago • 0 comments

The documentation specifies⬇️

// Filter is instantiated by DI so you can get parameter by constructor injection.

But only shows how to add global filters where the instance is instantiated upfront

var app = ConsoleApp.Create(args, options =>
{
    options.GlobalFilters = new ConsoleAppFilter[]
    {
        new MutextFilter() { Order = -9999 } ,
        new LogRunningTimeFilter() { Oder = -9998 }, 
    }
});

Is there a way to use Dependency Injection with global filters, that I've just missed from the documentation?

e.g.

// filter class
public class MyFilter : ConsoleAppFilter
{
  private readonly ILogger<MyFilter> logger;
  public MyFilter(ILogger<MyFilter> logger)
  {
    this.logger = logger;
  }

  public override async ValueTask Invoke(ConsoleAppContext context, Func<ConsoleAppContext, ValueTask> next)
  {
    logger.LogInformation(context.MethodInfo.Name);
    await next(context);
  }
}

// and adding the filter
var builder = ConsoleApp.CreateBuilder(args, options =>
  {
    options.AddFilter<MyFilter>;
  });

wozzo avatar Aug 05 '22 15:08 wozzo