Self-locking constructor with a lock?

Is it possible for the class constructor to wrap a proxy server around itself? This code, unfortunately, throws a StackOverflowException.

void Main() { var thing = new Thing(); } public static readonly ProxyGenerator generator = new ProxyGenerator(); public class Thing { public Thing() { generator.CreateClassProxyWithTarget(this); } } 

I want to somehow guarantee that new instances of my class are wrapped in a proxy, instead of creating some kind of factory that creates the proxy instance.

0
source share
2 answers

As far as I know, what you want is not supported. If you have an open constructor without parameters, anyone can create your class.

Now this does not mean that you cannot get what you want - it will be a little more work. You may have an β€œinitialized” flag in the class that is internal (only classes in your assembly can access it). A factory will be used to instantiate the proxy and set the initialized flag to true. Only the factory flag will set this flag. Each public method in your class can perform a check to make sure that the "initialized" flag is true, and throws an exception if it is false (this means that "more work" is coming - you will have to manually add this check to each method). New instances cannot set the initialization flag due to its scope.

This will not prevent someone from updating one of your classes, but at least will not allow them to use it. As for serialization, you probably want to have some data classes and serialize them instead of your proxied classes.

0
source

The closest I came is to create a Singleton that returns a proxy. Here is an example:

 public class MySingleton { protected static MySingleton _instance = null; public static MySingleton Instance { get { if (_instance == null) { if (Simple.UseDynamicProxies) _instance = Simple.GetProxy(typeof(MySingleton)); else _instance = new MySingleton(); } return _instance; } } } 

Please note that the Simple class contains a "heavy lift" of the actual proxy creation, interception and logging, etc., as well as the UseDynamicProxies flag, so I can enable / disable the use of the proxy server in the whole solution.

0
source

Source: https://habr.com/ru/post/1447078/


All Articles