Is it possible to wrap a C# singleton in an interface? - c#

I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.
But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.
IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.
//Register instance at some starting point in your application
container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());
//This single instance can then be resolved by clients directly, but usually it
//will be automatically resolved as a dependency when you resolve other types.
IActiveSessionService session = container.Resolve<IActiveSessionService>();
You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.

You can't do this with interfaces since they only specify instance methods but you can put this in a base class.
A singleton base class:
public abstract class Singleton<ClassType> where ClassType : new()
{
static Singleton()
{
}
private static readonly ClassType instance = new ClassType();
public static ClassType Instance
{
get
{
return instance;
}
}
}
A child singleton:
class Example : Singleton<Example>
{
public int ExampleProperty { get; set; }
}
A caller:
public void LameExampleMethod()
{
Example.Instance.ExampleProperty++;
}

You can make all the other members of your singleton implement corresponding members in an interface. However, you are correct that the Instance property cannot be part of the interface since it is (and must remain) static.

Interfaces can not have instances in C#, I think you only need to:
Implement the singleton pattern (yes, you'll need a static attribute or method to get the instance, but everything else does not require to be static)
On the other hand, your singleton can implement an interface if you want, just remember that other classes can also implement that same interface

Related

Force a class to implement a specific constructor [duplicate]

Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?
You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:
Exceptions
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.
Operators
There is no contract that specifies that two classes can be summed (with operator+ in C#)
Is there any design pattern to work around this limitation?
What construct could be added to the language to overcome this limitation in future versions of C# or Java?
Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.
Other than in generics, it would be tricky to actually use these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.
I wrote about this a little while ago when facing a similar problem.
Not enforced at compile-time, but I have spent a lot of time looking at similar issues; a generic-enabled maths library, and an efficient (non-default) ctor API are both avaiable in MiscUtil. However, these are only checked at first-usage at runtime. In reality this isn't a big problem - your unit tests should find any missing operator / ctor very quickly. But it works, and very quickly...
You could use the Factory pattern.
interface Fruit{}
interface FruitFactory<F extends Fruit>{
F newFruit(String color,double weight);
Cocktail mixFruits(F f1,F f2);
}
You could then create classes for any type of Fruit
class Apple implements Fruit{}
class AppleFactory implements FruitFactory<Apple>{
public Apple newFruit(String color, double weight){
// create an instance
}
public Cocktail mixFruits(Apple f1,Apple f2){
// implementation
}
}
This does not enforce that you can't create instance in another way than by using the Factory but at least you can specify which methods you would request from a Factory.
Force Constructors
You can't. The closest that you can come is make the default constructor private and then provide a constructor that has parameters. But it still has loopholes.
class Base
{
private Base() { }
public Base(int x) {}
}
class Derived : Base
{
//public Derived() { } won't compile because Base() is private
public Derived(int x) :base(x) {}
public Derived() : base (0) {} // still works because you are giving a value to base
}
The problem in the language is that static methods are really second class citizens (A constructor is also a kind of static method, because you don't need an instance to start with).
Static methods are just global methods with a namespace, they don't really "belong" to the class they are defined in (OK, they have access to private (static) methods in the class, but that's about it).
The problem on the compiler level is that without a class instance you don't have a virtual function table, which means you cannot use all the inheritance and polymorphism stuff.
I think one could make it work by adding a global/static virtual table for each class but if it hasn't been done yet, there's probably a good reason for it.
Here is I would solve it if I were a language designer.
Allow interfaces to include static methods, operators and constructors.
interface IFoo
{
IFoo(int gottaHaveThis);
static Bar();
}
interface ISummable
{
operator+(ISummable a, ISummable b);
}
Don't allow the corresponding new IFoo(someInt) or IFoo.Bar()
Allow constructors to be inherited (just like static methods).
class Foo: IFoo
{
Foo(int gottaHaveThis) {};
static Bar() {};
}
class SonOfFoo: Foo
{
// SonOfFoo(int gottaHaveThis): base(gottaHaveThis); is implicitly defined
}
class DaughterOfFoo: Foo
{
DaughhterOfFoo (int gottaHaveThis) {};
}
Allow the programmer to cast to interfaces and check, if necessary, at run time if the cast is semantically valid even if the class does not specify explicitly.
ISummable PassedFirstGrade = (ISummable) 10;
Unfortunately you can't in C#. Here is a punch at it though:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.Instance.GetHelloWorld());
Console.ReadLine();
}
}
public class Foo : FooStaticContract<FooFactory>
{
public Foo() // Non-static ctor.
{
}
internal Foo(bool st) // Overloaded, parameter not used.
{
}
public override string GetHelloWorld()
{
return "Hello World";
}
}
public class FooFactory : IStaticContractFactory<Foo>
{
#region StaticContractFactory<Foo> Members
public Foo CreateInstance()
{
return new Foo(true); // Call static ctor.
}
#endregion
}
public interface IStaticContractFactory<T>
{
T CreateInstance();
}
public abstract class StaticContract<T, Factory>
where Factory : IStaticContractFactory<T>, new()
where T : class
{
private static Factory _factory = new Factory();
private static T _instance;
/// <summary>
/// Gets an instance of this class.
/// </summary>
public static T Instance
{
get
{
// Scary.
if (Interlocked.CompareExchange(ref _instance, null, null) == null)
{
T instance = _factory.CreateInstance();
Interlocked.CompareExchange(ref _instance, instance, null);
}
return _instance;
}
}
}
public abstract class FooStaticContract<Factory>
: StaticContract<Foo, Factory>
where Factory : IStaticContractFactory<Foo>, new()
{
public abstract string GetHelloWorld();
}
Well, I know from the wording of your question you are looking for compile-time enforcement. Unless someone else has a brilliant suggestion/hack that will allow you to do this the way you are implying the compiler should, I would suggest that you could write a custom MSbuild task that did this. An AOP framework like PostSharp might help you accomplish this at comiple-time by piggy backing on it's build task model.
But what is wrong with code analysis or run-time enforcement? Maybe it's just preference and I respect that, but I personally have no issues with having CA/FXCop check these things... and if you really want to force downstream implementers of your classes to have constructor signatures, you can always add rules run-time checking in the base class constructor using reflection.
Richard
I'm unsure as to what you are trying to achieve, can you please elaborate? The only reason for forcing a specific constructor or static method accross different classes is to try and execute them dynamically at run time, is this correct?
A constructor is intended to be specific to a particular class, as it is intended to initialise the specific needs of the class. As I understand it, the reason you would want to enforce something in a class hierarchy or interface, is that it is an activity/operation relevant to the process being performed, but may vary in different circumstances. I believe this is the intended benefit of polymorphism, which you can't achieve using static methods.
It would also require knowing the specific type of the class you wanted to call the static method for, which would break all of the polymorphic hiding of differences in behaviour that the interface or abstract class is trying to achieve.
If the behaviour being represented by the constructor is intended to be part of the contract between the client of these classes then I would add it explicitly to the interface.
If a hierarchy of classes have similar initialisation requirements then I would use an abstract base class, however it should be up to the inheriting classes how they find the parameter for that constructor, which may include exposing a similar or identical constructor.
If this is intended to allow you to create different instances at runtime, then I would recommend using a static method on an abstract base class which knows the different needs of all of the concrete classes (you could use dependency injection for this).

Is casting a constructor parameter from interface type to concrete class type wrong here?

Given is the following class:
public interface ISession {}
public class Session : ISession
{
internal Uri ServerUri { get; private set; } // not in interface obviously
}
Now I have another class in the same project which depends on Session:
public interface IDataClass {}
internal DataClass : IDataClass
{
private readonly Session _session;
public DataClass(ISession session)
{
_session = (Session) session;
}
// some more methods that access the internal property _session.ServerUri
// and call methods on the session object
// ...
}
So actually the Session class is pretty complex. For unit testing the DataClass I made the constructor parameter an ISession, so I was able to mock the dependency and verify certain method calls on the ISession mock.
However, some methods in the DataClass have to access the _session.ServerUri property, so the field has to be of type Session rather than ISession.
I could also make the field of type ISession and cast the field everytime I access the internal property which would make it more clear in this specific location why the concrete, internal class is even needed.
Everytime I implement casts in the above way I wonder somehow if with better code design the cast could have been avoided. Oftentimes I found a better way and got rid of the cast.
But what about the example above? Is this good code design? Or is there a cleaner way? I just feel like initializing fields from constructors the above way is weird.
Honestly I think your current system isn't a good idea.
Your constructor is declaring "I'll take anything as long as it implements ISession", but that's not really true - calling code could find this out the hard way when they get an InvalidCastException upon trying to create a DataClass instance.
So you really ought to be declaring ServerUri in either ISession or an interface inherited from ISession - but in either case, you need to declare (and store) this dependency by interface only on DataClass
You are correct, casting like this is error-prone, because the compiler has no easy way of telling that it's going to fail.
However, it looks like the root of the problem is lack of access to the ServerUri property, so you added a cast as a workaround. If that is the case, you should be able to have it both ways - keep the interface, and have access to the property, if you can add a new interface:
public interface ISessionWithServerUri : ISession { // Come up with a better name
Uri ServerUri {get;}
}
Now your Session class can implement ISessionWithServerUri, letting you change the declaration of _session from Session class to ISessionWithServerUri interface:
internal DataClass : IDataClass
{
private readonly ISessionWithServerUri _session;
public DataClass(ISessionWithServerUri session)
{
_session = session; // Look, no cast!
}
// some more methods that access the internal property _session.ServerUri
// and call methods on the session object
// ...
}
Since DataClass depends on Session then it should declare that it in its constructor. Any clients of that class should be able to create a valid instance from the types/contracts defined in the constructor.
If you want to depend on an interface, then you should create a new one with the members you require e.g.
public interface IUriSession : ISession
{
Uri ServerUri { get; }
}
and change your constructor to
public DataClass(IUriSession session) { ... }
I would always try to avoid the explicit type casts like you have in the constructor. I am assuming you are using an IoC container to resolve your dependencies, and if the concrete type mapping ever changed to a different class that implemented that interface (and didn't have that internal property) this would obviously break. It also kind of defeats the purpose of the dependency injection being used in that class.
Are you able to change the DataClass's constructor to inject a different type? If so, you could create an interface that implemented ISession and also contained that ServerUri property, create a class that implemented the new interface and then inject that type into your constructor (the interface).

A static factory method on a generic or a non-generic class?

I have a generic class, let's call it MyClass<T>, which will need to have a factory method so to abstract constructor details away from client code.
Which of the two options is correct? (example instantiation code included)
Static non-generic factory method on the original generic MyClass<T>:
MyClass<SomeType> instance = MyClass<SomeType>.CreateNew();
Static generic factory method on a dedicated, non-generic static MyClass implementation:
MyClass<SomeType> instance = MyClass.CreateNew<SomeType>();
On the first sight, looks like proper answer to your question is #1. This is because your class is MyClass<T> and hence factory should also be T-specific. But there is more into it than this simple answer.
Before proceeding, I would add the third possibility: non-static factory class. Object which relies on a factory would have a public property through which it receives a factory object. Getter of the property would instantiate default factory if no other instance has been assigned. This allows dependency injection later, and also helps write unit tests that rely on their own fake factory. Solution would look something like this (ignore generics for a moment):
public class ISomeFactory { ... }
public class DefaultSomeFactory: ISomeFactory { ... }
public class ClientClass
{
public ISomeFactory FactoryOfSome // Right place for dependency injection
{
get
{
if (_fact == null)
_fact = new DefaultFactory();
return _fact;
}
set { _fact = value; }
}
private ISomeFactory _fact;
}
Now as I said, your class goes with generic parameter MyClass<T> and then factory should go with generic parameter as well: Factory<T>. This solution is better than generic method on general factory, simply because creating an instance may be T-specific. Solution with generic factory allows you this:
public class SpecialSomeFactory: DefaultSomeFactory<string> { ... }
In this way, you can override behavior of existing factory class and have an alternative way to generate instances that are specialized for strings. This is important because dealing with strings is often much different than dealing with primitive types like int or double. Having an opportunity to specialize the factory may be beneficial. But now you see why it might be a bad idea to have a static factory - statics cannot be extended.
Both examples are essentially variations on the service locator pattern. Controversially, this is often considered an anti-pattern as the dependencies of a class that uses it are not visible to its consumers.
A way to make your dependencies more explicit would be to adopt a solution similar to the first example, but make CreateNew() an instance method, as opposed to a static one.

How to create a collection of singletons from all classes in a namespace

Lets say we have a namespace called AllFoos.
And Lets say all classes in the AllFoos namespace implement a specific interface called IFoo and are all singletons.
Now we have:
HashSet<IFoo> myFoos = new HashSet<IFoo>();
What would be the code to populate the collection MyFoos with the singleton instances of all the classes in AllFoos?
The singleton implementation for all of these classes is:
private static IFoo _instance = new ConcreteImplementationOfFoo1();
public static IFoo Instance
{
get
{
return _instance;
}
}
If you would use a dependency injection framework you could:
register your classes as "singleton" in the container
register all implementations easily (good frameworks allow mass-registration based on some patterns)
resolve all implementations of your interface as a list
If you want to go the classic way, you have to tell how your singleton pattern looks like (e.g. static Instance property?), and it can be solved with classic reflection as mentioned in the comments already.

Can we inherit singleton class?

Can we inherit singleton class?
It depends on implementation. Singletons usually have private constructor and possibly marked sealed, if it is so then you can't. If it is at least protected you can. If you just inherit from singleton class, result will not be singleton so you should follow the pattern and make it also singleton.
Yes you can. Keep base class constructor protected (and not private).
Then derived class can be instantiated but base class cannot be (even inside function definitions of derived class). I've tried this and it works well.
If you cannot inherit from a singleton class, you might as well have implemented that class using only static methods, properties, fields and events.
Being able to access an object of a derived class through a static method (or property) of the base class is one of the key concepts of the Singleton pattern. To quote from Design Patterns: Elements of Reusable Object-Oriented Software (Gamma et. al.):
Applicability
Use the Singleton pattern when
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
(emphasis by me)
Here's a possible way to handle a derived Singleton:
public abstract class Singleton<T> where T : Singleton<T>, new() {
private static readonly T s_instance = new T();
protected Singleton() {
if (s_instance != null) {
string s = string.Format(
"An instance of {0} already exists at {0}.instance. " +
"That's what \"Singleton\" means. You can't create another.",
typeof(T));
throw new System.Exception(s);
}
}
public static T instance { get { return s_instance; } }
}
public class MyClass : Singleton<MyClass> {
}
Sure. Why not? The inheriting class will be a specialization of the base Singleton class.
Instances of each of these classes (the base class and the specialized one) will be completely separate. In other words, their Instance members will point to separate objects.
Only the singleton class itself can create an instance... so I supposse the answer is not. I think you can do it, but then it will not be a singleton any more :D

Categories