Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core dependency injection issue - AddScoped not creating a new instance

I've been using asp.net core dependency injection and I have seen an not expected behavior, at least for me. I'm adding a new service to the container like this:

services.AddScoped<IMyClass>(provider =>
{
   return new MyClass(
      "anyValue"
   });

After that, I inject the class into another class to use it:

public class AnotherClass(IMyClass xxx){

}

The thing is that there are a couple configurations that are made on the MyClass constructor based on request information. The problem is that I've seen the MyClass constructor be executed at the application startup only. After that, the class seems to use the same instance for all calls. As I'm using Scoped service I'm expecting to have a new instance for each request, am I wrong?

Thanks.

like image 250
Eduardo Lanfredi Avatar asked May 17 '18 00:05

Eduardo Lanfredi


People also ask

How can dependency injection be resolved?

Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.

What is AddScoped in .NET core?

AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.

How do I get an instance of IServiceProvider in .NET core?

An instance of IServiceProvider itself can be obtained by calling a BuildServiceProvider method of an IServiceCollection. IServiceCollection is a parameter of ConfigureServices method in a Startup class. It seems to be magically called with an instance of IServiceCollection by the framework.

Is AddSingleton thread safe?

Thread safety The factory method of a singleton service, such as the second argument to AddSingleton<TService>(IServiceCollection, Func<IServiceProvider,TService>), doesn't need to be thread-safe. Like a type ( static ) constructor, it's guaranteed to be called only once by a single thread.


1 Answers

Ok. The problem was that the class that was receiving the injection was added to the container as singleton. I just changed it to Scoped and everything worked well.

Thanks!

like image 73
Eduardo Lanfredi Avatar answered May 25 '23 10:05

Eduardo Lanfredi