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, for some reason, you need the factory and the constructed class to be in separate assemblies (which means simply using
internal
won't work), and you can ensure that your factory gets a chance to run first, you can do this:Yes, it's cumbersome and awkward. But there may be weird situations where this is actually a good solution.
It will always be created by calling new somewhere, but if you only want that to happen in your factory class, you can set all the constructors to Internal (or Private, and use a Public Static factory method on the same class).