views:

241

answers:

1

Hi,

is there is anyway to map/register singleton, using the unity configuration file, and map it to an interface while the singleton doesn't expose any public constructor?

Please advice,

Thanks

+1  A: 

You have use a class that exposes an internal (as a minimum) constructor if you want unity to create an instance of it. On the other hand you could write a container extension for unity that can use private constructors via reflection. Another alternative is to write a custom class that has a public constructor and also implements the interface. It then talks to your singleton, something like:

public class SingletonCreator: ISingleton
{
  public int SomeMethodInsideInterface()
  {
    return RealSingleton.Instance.SomeMethodInsideInterface();
  }

I would prefer the extension method though, something like this code (below) should get you into the private constructor. Then you would use this container extension in you config in order to tell unity to use your extension.

ConstructorInfo[] constructors = typeToConstruct..GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
Johan Leino