Correct way to clean up a "Pre" instance of ServiceCollection and ServiceProvider?

296 Views Asked by At

I am implementing a Custom Configuration Provider in my application.

In that provider, I have to make a REST API call. That call needs a valid OAuth 2 Token to succeed. To get that token I need a semi complicated tree of class dependencies.

For the rest of my application, I just use dependency injection to get the needed instance. But a custom configuration provider is called well before dependency injection is setup.

I have thought about making a "Pre" instance of dependency injection. Like this:

IServiceCollection services = new ServiceCollection();
// Setup the DI here
IServiceProvider serviceProvider = services.BuildServiceProvider();
var myTokenGenerator = serviceProvider.GetService<IMyTokenGenerator>();

But I have read that when you make another ServiceCollection, it can cause problems. I would like to know the way to avoid those problems.

How do I correctly cleanup a "pre-DI" instance of ServiceCollection and ServiceProvider?

(Note: Neither one seems to implement IDisposable.)

1

There are 1 best solutions below

2
On

Hm, I don't get the point why you want to do it that way. I'd probably get the Serviceprovider fully build.

To avoid that retrieved services affect each other I'd would use nested containers/scopes which means that if you retrieve retrieve the same service you get different instances per container/scope.

Hopefully I understood what you want to achieve. See .NET Core IServiceScopeFactory.CreateScope() vs IServiceProvider.CreateScope() extension