简体   繁体   中英

How to create a singleton at the start of a grpc service?

I have a service that should be created at the start of the application and I want to provide information about the service to the outside of the program.

My idea is a gRPC server (.NET Core 3.1) that creates the service at the start of the program and forwards the service to the gRPC controller using the default IoC container. My service should also be able to use other services using the default IServiceProvider (eg for logging).

My first approach was to create the service in ConfigureServices and passing the instance to AddSingleton . That did not work, because my service needs the IServiceProvider that hasn't been built in ConfigureServices yet.

I then found out that you can specify a factory that takes the service provider as an argument:

services.AddSingleton<IService>(serviceProvider => new Service(serviceProvider));

Now, my service gets access to all other services but it is only being created once a gRPC client requests information about the service.

Is there a way to instantly instantiate the service?

Thank you in advance.

You can create an instance of ServiceProvider at anytime inside ConfigureServices using services.BuildServiceProvider() and pass it to your Service singleton. Do note, however, that all services registered in the IServiceCollection after you create the ServiceProvider will not be accessible through the provider. For example:

public void ConfigureServices(IServiceCollection services)
{
    var sp = services.BuildServiceProvider();
    var service = new Service(sp);
    services.AddSingleton(service);

    // ...

    services.AddScoped<IOtherService, OtherServiceImplementation>();
    var otherService = sp.GetService<IOtherService>();
    // otherService == null
}

So... if you cannot wait with creating the singleton until access to it is requested, you should ensure that it's only created after all other necessary services have been registered.

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