Skip to main content

ASP.NET Core–Cannot resolve from root provider because it requires scoped service

A colleague contacted me with the following problem; when running his ASP.NET Core application it failed with the following error message:

Cannot resolve IApiLoggingService from root provider because it requires scoped service NHibernate.IInterceptor

In this post I walk you through the different steps we took to investigate the issue and explain how we solved it.

But before I dive into the problem itself I first want to give some background info on dependency injection in ASP.NET Core and service lifetimes.

Dependency injection and service lifetimes

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.

Registration of a dependency is done in the built-in service container, IServiceProvider. Services are typically registered at the app's start-up and appended to an IServiceCollection. Once all services are added, you use BuildServiceProvider to create the service container.

    Injection of the service is done into the constructor of the class where it's used. The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it's no longer needed.

    Services can be registered with one of the following lifetimes:

    • Transient: A service is created each time they’re requested from the service container
    • Scoped: A service is created once per client request(typically an HTTP request in ASP.NET Core)
    • Singleton: A service is created once per lifetime of the service container

    Diving into our problem

    If we take the knowledge above and apply it to the error message we got, we could assume that the following is happening:

    We have registered two services:

    • An IApiLoggingService with either a transient or singleton lifetime
    • An IInterceptor with a scoped lifetime

    The IApiLoggingService has a dependency on the IInterceptor.  We are resolving the IApiLoggingService from the root container(the root container is used when there is not  a scoped context (e.g. a specific HTTP request) available.

    As there is no scope available, it is not possible to create the IInterceptor service with a scoped lifetime.

    Remark: The error is caused by the built-in scope validation. If a scoped service is created in the root container, the service's lifetime is effectively promoted to singleton which is of course not what we want. Scope validation prevents this.

    Let’s dive into the application to confirm this…

    We first take a look at the service registrations:

    And indeed we have both a transient and scoped registration.

    Now we look at the ApiLoggingService implementation and we see that the IInterceptor is injected as a dependency:

    And then we check where the IApiLoggingService is injected:

    We see that it is used inside an ASP.NET Core middleware and is injected into the constructor. Convention based middleware is created and instantiated before a specific request arrives so that explains the error above.

    Does this mean that we cannot use scoped services inside ASP.NET Core middleware?

    Fortunately we can use scoped services inside our middleware. Instead of injecting our dependency through constructor injection, we could inject our service in the Invoke method through method injection when using convention based middleware:

    Another option is to switch to factory based middleware which I’ll explain in my next post.

    More information

    Dependency injection in ASP.NET Core | Microsoft Learn

    Popular posts from this blog

    Podman– Command execution failed with exit code 125

    After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

    Cache stampede: when our cache turned against us

    While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

    A complex system designed from scratch never works

    A few years ago, I worked as an architect on a big mainframe rewrite. I still count it as one of my failures. Not because the technology was wrong, but because I couldn't convince the management team to simplify the approach. Years later, the organization is still struggling to get the new system up and running. I left the project at the time, because I couldn't put my name behind an approach that would take very long and cost a lot of money without a working system to show for it along the way. Gall’s Law That memory keeps coming back to me, because it's a textbook case of Gall's Law playing out in real life. Gall's Law , from John Gall's Systemantics , states it plainly: A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works, and it cannot be patched to make it work. You have to start over with a simple system that works. What does that mean in practice,...