user2818430
user2818430

Reputation: 6029

ASP.NET Core access service in Startup.cs ConfigureServices method

I need to access a service inside ConfigureServices method in Startup.cs and I do this:

services.AddScoped<ICustomService, CustomService>();

var sp = services.BuildServiceProvider();

var service = sp.GetService<ICustomService>(); // this is null

However var service above is always null.

What do i do wrong?

Upvotes: 3

Views: 1538

Answers (1)

GPW
GPW

Reputation: 2626

I had this sort of problem - I had a singleton 'settings' service which I wanted to use. I solved it by Actually creating one then registering that exact instance with DI via the overload that lets you specify a 'provider', rather than just registering the class, and adding a nice big comment explaining this:

var settingsService = new SettingsService(_hostingEnvironment);

//Add a concrete settings service which is then registered as the de facto settings service for all time.
//we need to do this as we want to use the settings in this method, and there isn't a satisfactory method to 
//pull it back out of the IServiceCollection here (we could build a provider, but then that's not the same provider
//as would be build later... at least this way I have the exact class I'll be using.
services.AddSingleton<ISettingsService, SettingsService>((p) => settingsService);

..
..
..
var thing = settingsService.SomeSettingIWant();

If what you want isn't a singleton but is something transient, then I guess you can just create a concrete class for it right there? I know it probably feels a bit like cheating, but it would work fine...

Upvotes: 1

Related Questions