If for some reason you need a factory and the built class in separate assemblies (which means that just using internal will not work), and you can make sure that your factory gets a chance to start, you can do this first:
// In factory assembly: public class Factory { public Factory() { token = new object(); MyClass.StoreCreateToken(token); } public MyClass Create() { return new MyClass(token); } private object token; } // In other assembly: public class MyClass { public static void StoreCreateToken(object token) { if (token != null) throw new InvalidOperationException( "Only one factory can create MyClass."); this.token = token; } public MyClass(object token) { if (this.token != token) throw new InvalidOperationException( "Need an appropriate token to create MyClass."); } private static object token; }
Yes, it is cumbersome and uncomfortable. But there may be strange situations when this is a really good solution.
munificent 08 Sep 2018-10-10T00: 00Z
source share