Search code examples
asp.netsingletondisposesimple-injector

Simple Injector ASP.NET Singleton Dispose


Simple Injector documentation is quite clear on both transient and singleton registrations, and how they will be disposed etc. Docs indicate that singletons registered with all but the pre-constructed objects will get disposed when the container gets disposed.

My question specifically involves a singleton registration that I Need to be disposed when the ASP.NET application gets disposed (I send any remaining messages when that service is disposed). Most of my registrations are transient and get disposed when each request is disposed. When debugging in VS/IISExpress, I don't ever see when my singletons get disposed - or when the container itself ultimately gets disposed. In my console apps & azure services I simply call container.Dispose() when I'm done. Any clues in ASP.NET for this final cleanup?


Solution

  • For singletons to be disposed, you need to explicitly call Container.Dispose() when the application ends. This can be done for instance in the Application_End event in your Global.asax. But please be warned.

    I send any remaining messages when that service is disposed

    This seems like a very bad idea, because there are many reasons why an Application_End event doesn't run. IIS can quite aggressively kill applications, and so will do power outages and other hardware malfunctions. If that happens, it means that you will lose any messages that are still in the local buffer.

    This might not be a problem for volatile messages that are used for application heartbeats and sometimes logging, but if those messages describe important business events, you should use durable queuing or storage mechanisms.

    When debugging in VS/IISExpress, I don't ever see when my singletons get disposed

    That can very well be. When debugging a web application, the web application never stops by itself. In case you stop debugging either the application is abruptly stopped without having a chance to run any finalizers and clean-up methods, or when you stop debugging, the application keeps running in the background; which still means you won't see any clean-up happening.