1

I realize DI (ctor based) in .NET CORE is quite straight forward but if it comes to nested injections I struggle.

This is quite simple:

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddRavenDbDocStore(x => x.AfterInitializeDocStore = RavenConfiguration.AfterInitializeDocStore());
            services.AddRavenDbAsyncSession();
            services.AddSingleton(new ExceptionHelper());
            services.AddScoped<ICompoundService>(x => new CompoundService(x.GetService<IAsyncDocumentSession>(), x.GetService<ExceptionHelper>()));

But whenever I need to register a type within e.g a lamba of another registration, I have problems resolving dependencies:

 services.AddMvc(setup =>
            {
                ILogger logger; // how would I get that?
                setup.Filters.Add(new ApiExceptionFilter(logger));
            }).AddFluentValidation();

Is there a good way to deal with that? I certainly do not want to call this in ConfigureServices

    var sp = services.BuildServiceProvider();

I read about this in Resolving instances with ASP.NET Core DI from within ConfigureServices but I do not reall see an elegant option here...

Update: After reading comments I realized that you can register Filters per type:

setup.Filters.Add<ApiExceptionFilter>()

Then you would not have to pass dependencies in the first place. Still I wonder if there is a best practice for similar scenarios where you cannot access ServiceProvider in the lambda.

yBother
  • 648
  • 6
  • 25
  • 1
    Why use that code? Why not `Filters.Add(typeof(ApiExceptionFilter)` ? – Panagiotis Kanavos Nov 18 '21 at 10:05
  • 2
    Can't you do `setup.Filters.Add()` and let DI handle the rest? – DavidG Nov 18 '21 at 10:06
  • 1
    The [Dependency Injection section](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0#dependency-injection) in the Filters doc explains that for type-activated filters all dependencies will be populated, including loggers. – Panagiotis Kanavos Nov 18 '21 at 10:08
  • @yBother I already posted the link to the Filter docs that says otherwise. In the same section `Loggers are available from DI. However, avoid creating and using filters purely for logging purposes. The built-in framework logging typically provides what's needed for logging` – Panagiotis Kanavos Nov 18 '21 at 10:08
  • Okay I got it - using setup.Filters.Add() should work. Still I'd like to know if there would be an approach for resolving dependencies in lambdas that to not provide serviceprovider? Or is that considered to be unusual? because I really encountered that a few times already... – yBother Nov 18 '21 at 10:15

0 Answers0