How to get rid of warning "Calling 'BuildServiceProvider' from application code..."

Viewed 1218

I have the following code that shows the warning...

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

enter image description here

Here is an abbreviated snippet from ConfigureServices that shows how this is being used. Basically I need to resolve the AdminDbContext to pass it to the Initialize routine.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AdminDbContext>(o => o.UseSqlServer("config settings here"));

        CustomerConnectionStrings.Instance.Initialize(services.BuildServiceProvider().GetService<AdminDbContext>());
    }

What do I need to do to get rid of this warning?

I have seen other posts that show how to do this, but I am not making the connection for my specific use case.

2 Answers

While I believe this might be an XY problem.

I would advise following the suggestions in the warning

Consider alternatives such as dependency injecting services as parameters to 'Configure'.

//...

public void ConfigureServices(IServiceCollection services) {

    services.AddDbContext<AdminDbContext>(o => o.UseSqlServer("config settings here"));

    //...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AdminDbContext adminDb) {

    CustomerConnectionStrings.Instance.Initialize(adminDb);

    //...
}

@Nkosi answer is a correct but in the case someone is looking for an alternative you can get any service from the app:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AdminDbContext adminDb) {

    CustomerConnectionStrings.Instance.Initialize(App.ApplicationServices.GetService<IMyService>());

    //...
}

And another option for anyone who comes across this. Sometimes its better to work with singletons rather than static classes: When you intialize CustomerConnectionStrings you will request AdminDBContext and pass it there.

Related