Skip to content

Preventing a scoped dependency from being disposed #3011

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
fiksen99 opened this issue Mar 30, 2018 · 1 comment
Closed

Preventing a scoped dependency from being disposed #3011

fiksen99 opened this issue Mar 30, 2018 · 1 comment

Comments

@fiksen99
Copy link

fiksen99 commented Mar 30, 2018

We have a scenario where we:
Have an IMyClientFactory singleton, whose implementation is to output an IMyClient. It maintains an IMemoryCache of client's that is has used, and will return the cached IMyClient if present (the cache key is based around HttpContext.Items values) otherwise it will create a new IMyClient and return it. IMyClient is expensive to create. IMyClient implements IDisposable

The IMyClientFactory is registered as a singleton via services.AddSingleton<IMyClientFactory, MyClientFactory>()
The IMyClient is registered as a Scoped like so:

services.AddSingleton<IMyClient>(sp =>
            {
                var factory = sp.GetRequiredService<MyClientFactory>();
                return factory.GetClientAsync().Result;
            });

unfortunately, due to default scoping behaviour, myClient.Dispose() is called at the end of every request scope, this means that the cached client is now disposed and unusable.

We should provide a mechanism such the the dispose behaviour is not necessarily called at scope end time, perhaps a flag to the AddScoped/AddTransient methods such that dispose isn't automatically called.

Alternatively, we could provide a mechanism such that calling AddSingleton with a factory method will always call into the factory method?

@muratg
Copy link
Contributor

muratg commented Apr 3, 2018

We are closing this issue because no further action is planned for this issue.

@muratg muratg closed this as completed Apr 3, 2018
@ghost ghost locked as resolved and limited conversation to collaborators Dec 4, 2019
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants