profile
viewpoint

Ask questionsGet or Create Service and IDisposable

There is a note at the bottom of this section: https://github.com/davidfowl/DotNetCodingPatterns/blob/main/1.md#creating-instances-of-types-from-an-iserviceprovider

NOTE: Disposable instances created with this API will not be disposed by the DI container.

It's interesting to note that ActivatorUtilities also has a GetServiceOrCreateInstance method. However its not possible to tell when calling this API, if the instance returned was resolved from a registration, or was not registered and so a new instance was created. Given the note above, if the service was IDisposable - how can the consumer know if they are, or are not responsible for disposing the instance when obtaining services like this? It feels like the GetServiceOrCreateInstance method should supply an out parameter indicating whether the service was returned and is being tracked, or whether an instance was created and therefore is not being tracked ?

davidfowl/DotNetCodingPatterns

Answer questions thoemmi

@ExceptionCaught In your singleton, you will have to create your own scope, like

using (var scope = serviceProvider.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetService<DBContext>();
    // ...
}

Try to keep the scope's lifecycle as short as possible.

useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List