0

Problem: I have a provider class MyProvider that delivers DataContext instances to other handler. MyProvider keeps DataContext instances open for reuse. As this behaviour consumes a lot of memory I wanted MyProvider the create an instance of the DataContext on every request and to dispose it afterwards. As there are many handler requesting one DataContext at the same time via a Getter, I cannot be sure when to dispose the DataContext instance.

I guess there is no magic trick, that tells MyProvider.Getter, when the returned instance is not used anymore?

Thanks

user946924
  • 65
  • 6

1 Answers1

0

I chose to create a CreateDataContext() in my "MyProvider" class, and let the caller supply it in subsequent requests:

using (DataContext context = provider.CreateDataContext())
{
    provider.FirstMethod(context, ...);
    provider.SecondMethod(context, ...);
}

This way the caller can hang on to the context as long as it wants, but it can still be disposed as soon as it is no longer needed.

I don't know if this is the best solution, but it did solve my problem of such a context providing access to a limited resource.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72