Search code examples
c#entity-frameworkasp.net-coreautofac

Objects not being disposed when using child lifetimescopes


I have an ASP.NET 5 application which still uses EF6 and I register my services with Autofac as follows:

builder.RegisterType<UnitOfWork>()
    .As(typeof(IUnitOfWork))
    .InstancePerDependency();

builder.RegisterAssemblyTypes(assemblies)
    .Where(t => t.FullName.StartsWith("MyApp") && t.Name.EndsWith("Service"))
    .AsImplementedInterfaces()
    .InstancePerDependency();

Then in controllers I'm doing:

//Save object of type SomeObject
using (var scope = itemScope.BeginLifetimeScope())
{
    var someService = itemScope.Resolve<ISomeService>();
    var savedObject = await someService.SaveAsync(objectToSave);
}

The above runs in a loop in a background thread.

Originally I was not using child scopes. But then, using the diagnostic tools, I noticed that the SomeObject references are increasing and not being removed from the data context.

So I decided to add child scopes to have new instances every time. But this doesn't the problem. It stays as is.

If I'm using a child scope why does this happen, and how can I solve it?


Solution

  • You are still using itemScope to resolve the service. Note that scope was not used inside the using at all.

    //Save object of type SomeObject
    using (var scope = itemScope.BeginLifetimeScope())
    {
      //var someService = itemScope.Resolve<ISomeService>();
        var someService = scope.Resolve<ISomeService>();
        var savedObject = await someService.SaveAsync(objectToSave);
    }