Is the default IServiceProvider in ASP.NET Core thread safe?

I’m building a small ASP.NET Core app that also has a bunch of separate business logic that runs in its own thread. I was already using a IServiceProvider in the side program, so when I found out that ASP.NET Core also uses its own IServiceProvider, so I thought I could re-use only a single instance.

Now the question is, is the IServiceProvider that the web host uses thread safe? My setup basically looks like this

var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

Task.Run(() => {
  // here I access the IServiceProvider via `host.Services`
  new Foo(host.Services).Run();
});

host.Run();

The default service provider implementation. You can see services factories are stored in ConcurrentDictionary and building an expression for creating service object is executed in separate thread except the first one. And I am sure this expression is also thread-safe (likely stateless). So the default ServiceProvider is thread-safe.

Leave a Comment