DerivedTypeConstructorSelectorPolicy Memory Leak?

Dec 5, 2012 at 8:44 AM

So we're running into a problem where the container is holding onto instances of DerivedTypeConstructorSelectorPolicy for the duration of the application. This wouldn't be so bad were it not for the fact that the following two lines of code in TypeInterceptionStrategy wraps the old policy into a new one, which then now holds onto two instances (or more, every call to Resolve for an intercepted class will compound the problem). You can see this when running .NET Memory Profiler.

      IConstructorSelectorPolicy originalConstructorSelectorPolicy = PolicyListExtensions.Get<IConstructorSelectorPolicy>(context.Policies, (object) context.BuildKey, out containingPolicyList);
      PolicyListExtensions.Set<IConstructorSelectorPolicy>(containingPolicyList, (IConstructorSelectorPolicy) new TypeInterceptionStrategy.DerivedTypeConstructorSelectorPolicy(proxyType, originalConstructorSelectorPolicy), (object) context.BuildKey);

This is causing thrashing of the Gen 2 collection when you have a lot of classes being intercepted and then you get holes in memory that the GC cannot reclaim, especially as policies get copied to ensure thread safety. Once you have a sufficient number of items in the policy list, it will get moved to the LOH, which makes the thrashing even worse.

I should caveat this with the fact that our application is running in IIS Classic and not Integrated Pipeline and in 32-bit mode, double whammy, I know. With more addressable space in 64-bit mode, this wouldn't be so bad. But still, we're stuck with the virtual memory that is given to us by IIS and this goes quickly as the GC can't find enough space in the VM map to allocate additional memory and requests start dying.

The file only has 3 revisions, with the original revision looking like it did not have this issue. Has anyone else run into this problem or am I missing something that perhaps explains this behavior?

A link to a very simple program that illustrates this is posted on pastebin:

Using .NET Memory Profiler (or your profiler of choice) and watching for the DerivedTypeConstructorSelectorPolicy, you can watch it grow through each iteration and as it grows, you can examine and see the originalConstructorSelectorPolicy keeps referencing the old instance in a long chain.

As an example of how many classes we intercept, it's on the order of about 1300 or so registrations.


Dec 5, 2012 at 8:20 PM
Edited Dec 5, 2012 at 8:23 PM

I found the answer and posted it on StackOverflow:

This seems like a legitmate bug. Filed a bug report: