Dispose IOC container gracefully on application shutdown

Vote:
 

I have a solution in which I spin up a service as a singleton instance. It inherits IDisposable in order to properly flush and clean up internals. However, the Dispose method is never called, because the StructureMap container itself is never disposed by Episerver.

I attempted to call IContainer.Dispose from a IConfigurableModule.Uninitialize method. But I cannot touch the IContainer in any context other context than IConfigurableModule.ConfigureContainer.

It would be very nice if you could make the IServiceConfigurationProvider interface inherit from IDisposable, and then explicitly dispose it on shutdown. Because then I would be able to remove my custom solution to this problem.

#216189
Edited, Jan 29, 2020 10:00
Vote:
 

how does your custom solution look like?

#216285
Feb 01, 2020 11:27
Vote:
 

Hi Valdis

I came up with a very simple fix (see below). Going to try an OWIN variant of it.

But still, I would rather have Episerver dispose of the container internally in the InitializationEngine.

public class ContainerDisposalInitialization : IConfigurableModule
{
	public void ConfigureContainer(ServiceConfigurationContext context)
	{
		var container = context.StructureMap();
		if (HostingEnvironment.IsHosted)
		{
			// Keep a reference to the container, and register a custom shutdown handler instance.
			HostingEnvironment.RegisterObject(new DisposeServicesOnShutdownHandler(container));
		}
	}
	
	public void Initialize(InitializationEngine context) { }
	public void Uninitialize(InitializationEngine context) { }
}

public class DisposeServicesOnShutdownHandler : IRegisteredObject
{
	private readonly IContainer _container;

	public DisposeServicesOnShutdownHandler(IContainer container)
	{
		_container = container;
	}
	
	// When IIS is shutting down, this Stop method will be called.
	// This gives us a chance to dispose the StructureMap container.
	// StructureMap then calls Dispose() on singleton services that supports it.
	public void Stop(bool immediate)
	{
		_container?.Dispose();
		
		HostingEnvironment.UnregisterObject(this);
	}
}
#216291
Feb 02, 2020 7:26
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.