How do I make sure that a certain class is only instantiated by a factory and not by calling new directly?
EDIT: I need the factory to be a separate class (for dependency injection purposes) so I can't make it a static method of the class to be instantiated, and so I can't make new private.
If the factory is in the same assembly and you only need protection against external assemblies instantiating the class, you can make the constructor internal. The only way I know to prevent this for all other classes (including those in the same assembly) is to make the instantiated class a nested private class of the factory and only expose it as an interface. If the class is its own factory (a static factory method), then you can make the constructor private, as others have mentioned.
Make its constructors private and supply the factory method as a static method on the class itself.
In most cases you can just make the constructors internal, allowing you to break the factory out into its own class - I've found it's often not worth trying to prevent my own team from using new
to create instances within the class' assembly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With