profou
profou

Reputation: 217

Singleton pattern by using Unity

Unity allows to create a singleton with:

this.UnityContainer.RegisterType<MyClass>(new ContainerControlledLifetimeManager());
var instance = this.UnityContainer.Resolve<MyClass>();

The access to the MyClass's constructor must be public to allow the container to be able to create a new instance (for another project like a module, ...).

In this case, developers can still create a new instance by using the constructor directly:

var instance = new MyClass();

How do I prevent developers from doing this?

Another way is to create an instance (constructor access of the class is private now - singleton pattern) and register it with unity like below, I lose the dependency property injection, and my workaround is to use the service locator to initialize the dependency properties in the static method Instance:

this.UnityContainer.RegisterInstance<MyClass>(MyClass.Instance);

What is the best way to define the singleton pattern in both cases simultaneous (with and without unity)?

Upvotes: 1

Views: 2333

Answers (2)

Tooly
Tooly

Reputation: 35

You only have to use the singleton pattern. An example you can find here: Singleton Pattern

public class Singleton {
 private Singleton instance = new Singleton();

 private Singleton() {}

 public Singleton getInstance() {
    return instance;
 }
}

Upvotes: 0

Haukinger
Haukinger

Reputation: 10863

Hide the class away from your users if you want to prevent them from creating it.

That means creating a public interface for your class, while the class itself is not public. Having an interface for your service is a good idea anyway, think of unit testing, for example...

Several options come to mind for the non-publicness of your service implementation:

  • put it in a different assembly and make it internal
  • put it in another class and make it private

But be aware of the fact that malicious users can always use reflection to create their own instances... no 100% safety.

Upvotes: 1

Related Questions