I have a windows service, which contains a singleton which in turn uses some loggers, message queue listeners and so on. Those classes implements IDisposable
. S
I'd rather not implement IDisposable
on singleton: IDisposable
provokes developer to Dispose the (single) instance:
using(var temp = Temp.Instance) {
...
}
which leads to (possible) crash in some other part of the application (since the single Temp
instance has been disposed):
Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed
In some rare case if you have to release some resouces aquired, I'd use ProcessExit
event
public class Temp {
private static readonly Lazy instance = new Lazy(() => new Temp());
private void OnProcessExit(Object sender, EventArgs e) {
// Release native resource if required:
// some resources e.g. files will be closed automatically,
// but some e.g. transactions should be closed (commit/rollback) manually
try {
...
}
finally {
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
}
}
private Temp() {
// create IDisposable objects which use native resources
// If you have to release some resouces on exit
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
public static Temp Instance {
get {
return instance.Value;
}
}
}