1

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)?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
 }
}

2 Comments

If you want to do this, at least do it using Lazy... and you have to use static, and that would be rather weird if there's a DI container in place already.
As I said earlier, I lose the dependency property injection if I do that ... I don't want it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.