Skip to content

Fix memory leak caused by use of ThreadLocal<bool> inside CyclicDependencyValidator #956

@dotnetjunkie

Description

@dotnetjunkie

Simple Injector's internally creates a CyclicDependencyValidator instance per registration. Each CyclicDependencyValidator uses its own ThreadLocal<bool> instance, but this causes severe memory pressure (leak) when uses in combination with a large amount of registrations or with a large amount of container instances.

Related:

A ThreadLocal<T> causes a memory leak in case its not disposed of properly. Although the amount of memory isn't that big, it will count up in case many ThreadLocal<T> instances are created, as is the case with the CyclicDependencyValidator. Each InstanceProducer has its own CyclicDependencyValidator intance, and although the InstanceProducer removes the reference to its CyclicDependencyValidator when its no longer of use, the underlying ThreadLocal<bool> is not disposed of.

This causes memory issues as reported by @andreminelli here:

We took a memory dump and analyze it. We have spotted very large arrays (4 Million in length, in some cases) of ThreadLocal<bool>.LinkedSlotVolatile on LOH, the majority of them "attached" to CyclicDependencyValidator. This sample had about 6GB, and LOH allocated spaced (which was very fragmented) was about 2GB.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions