Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac Garbage Collection - BeginLifetimeScope

Tags:

autofac

I have created a windows service to build and send emails. I have implemented dependency injection and I'm using Autofac as the DI container.

My problem is that as the service runs the allocated memory keeps growing, at the moment it is over 1GB. I read this article about lifetimes and from this I incorporated the BeginLifetimeScope, rather than resolving directly from the container. But this hasn't solved the problem. Any advice appreciated.

Below is the Autofac configuration which is in my service onStart method.

ContainerBuilder builder = new ContainerBuilder();

//Register the Database context
builder.RegisterType<DbContainer>().As<IDbContainer>();

//Register a single shared instance of Email Manager which will be shared by all EmailProcessing instances
builder.Register(c => new EmailManager()).As<IEmailManager>()).SingleInstance();

//Register email processing classes
builder.Register(c => new EmailBuilder(c.Resolve<IDbContainer>(), c.Resolve<IEmailManager>())).As<IEmailBuilder>();

_container = builder.Build();

Below is the email timer method which runs every 5 seconds.

private void EmailTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
     using (var lifetime = _container.BeginLifetimeScope())
     {
          //Builder, and any of its disposable dependencies, will
          //be disposed of when the using block completes
          IEmailBuilder builder = lifetime.Resolve<IEmailBuilder>();
          //Execute the process emails method
          builder.ProcessEmails();
     }

     emailTimer.Start();
}

I want the same instance of EmailManager to be used with every email timer iteration, but a new instance of everything else.

EDIT

Is there a way to check if EmailBuilder and all of its dependencies have been disposed and are ready for GC?

A lot of my objects are going into Generation2 and are being held onto. Should they not be disposed when the lifetime has completed?

like image 249
ministrymason Avatar asked Nov 03 '22 16:11

ministrymason


1 Answers

The Autofac setup looks fine. Are you sure the DbContainer is releasing all resources?

like image 188
Peter Lillevold Avatar answered Nov 11 '22 16:11

Peter Lillevold