.NET Core Singleton Creation is called multiple times

前端 未结 2 2131
清歌不尽
清歌不尽 2021-02-19 15:34

I\'m registering a service as a singleton in .NET Core. Yet I\'m seeing the constructor for the singleton called multiple times.

services.AddSingleton

        
2条回答
  •  梦毁少年i
    2021-02-19 15:55

    You can declare a dependency on IServiceProvider -- don't build it, inject it.

    public class SomeController
    {
        DbAuthorizationOptions authOptions;
        public SomeController(IServiceProvider provider)
        {
            authOptions = provider.GetSerivce();
        }
    }
    

    But this is the service locator anti-pattern. As I commented on NightOwl888's post after you gave more details, a factory is probably a better approach.

提交回复
热议问题