Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make sure object only created by factory (C#)

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.

like image 408
JoelFan Avatar asked Sep 08 '10 19:09

JoelFan


2 Answers

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.

like image 172
Dan Bryant Avatar answered Oct 02 '22 15:10

Dan Bryant


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.

like image 41
Jeff Sternal Avatar answered Oct 02 '22 13:10

Jeff Sternal