You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
The text was updated successfully, but these errors were encountered:
We have a scenario where we:
Have an
IMyClientFactory
singleton, whose implementation is to output anIMyClient
. It maintains anIMemoryCache
of client's that is has used, and will return the cachedIMyClient
if present (the cache key is based aroundHttpContext.Items
values) otherwise it will create a newIMyClient
and return it.IMyClient
is expensive to create.IMyClient
implementsIDisposable
The
IMyClientFactory
is registered as a singleton viaservices.AddSingleton<IMyClientFactory, MyClientFactory>()
The
IMyClient
is registered as a Scoped like so: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?The text was updated successfully, but these errors were encountered: