Skip to content

Memory leak when not assigning UnitOfWorkScope in using statement #2

Description

@spongessuck

When using IKernel.Get<T> in a using block, I was having issues with memory leaks as the objects created by IKernel.Get<T> were not being dereferenced and the GC never cleaned them up.

private IKernel kernel;
...
public T CreateInstance<T>()
{
    using(UnitOfWorkScope.Create())
        return this.kernel.Get<T>();
}

After refactoring like so, the problem went away:

public T CreateInstance<T>()
{
    T instance;
    using(var _ = UnitOfWorkScope.Create())
        instance = this.kernel.Get<T>();
    return instance;
}

The key was assigning the UnitOfWorkScope in the using statement. Even after moving the return outside of the using block, as soon as I removed the var _ = assignment the problem came back.

Not sure what to make of it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions