Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposable singleton in C#

I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?

The interface I would like is something like:

var x = Foo.Instance;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
             // also, it assumes no further operations on x/y will be performed.

Note - the pattern has to be thread-safe, of course.

Edit - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.

I would also prefer a pattern that can be reused, if possible.

like image 698
ripper234 Avatar asked Oct 22 '08 13:10

ripper234


People also ask

How do you dispose of a singleton instance?

your using statement is equivalent to what I have Singleton. Instance. Dispose and let's assume Dispose is thread safe (though it is not shown in my example), hence Instance is safe with a double-check locking. @kateroh: No amount of code in the Dispose method will fix the no-lock code in the Instance property.

What is a singleton C?

Singleton in C++ Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

What is Singleton pattern in C sharp?

One of the commonly used design patterns in C# is the singleton pattern. This design pattern uses a single instance of a class to enable global access to the class members. Instead of having several instances of the same class, singletons have just one instance, and provide convenient access to that single instance.

Is AddSingleton thread safe?

Thread safety The factory method of a singleton service, such as the second argument to AddSingleton<TService>(IServiceCollection, Func<IServiceProvider,TService>), doesn't need to be thread-safe. Like a type ( static ) constructor, it's guaranteed to be called only once by a single thread.


1 Answers

Mark Release as internal and use the InternalsVisibleTo attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as private and access it using reflection.

Use a finalizer in your singleton that calls the Dispose method on the singleton instance.

In production code, only the unloading of an AppDomain will cause the disposal of the singleton. In the testing code, you can initiate a call to Release yourself.

like image 173
Omer van Kloeten Avatar answered Sep 22 '22 00:09

Omer van Kloeten