简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM