0

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.)

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • This article might help https://www.jerriepelser.com/blog/disposing-services-using-dependency-injection-net-core-console-apps/ – Nkosi Sep 16 '21 at 01:21
  • the MS DI [internal Service Provider](https://source.dot.net/#Microsoft.Extensions.DependencyInjection/ServiceProvider.cs,f10e59a06d22bf0f) is disposable – Nkosi Sep 16 '21 at 01:22
  • _"Neither one seems to implement IDisposable"_ -> create a scope, which is disposable, and resolve services from it. – abdusco Sep 16 '21 at 06:17

1 Answers1

0

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

DotNetDev
  • 205
  • 1
  • 10
  • The normal service provider is not build at the time that Configuration is setup. And I need configuration to setup the ServiceCollection. I will add a scope to the things I resolve. That will help them not be in the way. I still wish I was sure of how to clean things up correctly. – Vaccano Sep 16 '21 at 20:22
  • I recently faced the problem, that I need some instances from the serviceprovider which is used together with lamar. I had to initialize a second lamar container (independent from host, etc...) – DotNetDev Sep 23 '21 at 14:18