I understand the usage of proxies in EF and I want to apply a similar pattern to an application I am creating. So basically, I want to create a dynamic class at runtime that inherits from an existing class, in order to add some extra properties that will allow me to keep track of certain things in my application. I have read a bit about the DynamicObject and RealProxy, but it is not evident to me how they would help me achieve similar behaviour like EF-proxies have.
Asked
Active
Viewed 63 times
0
-
1Possible duplicate of [How to make a simple dynamic proxy in C#](https://stackoverflow.com/questions/8387004/how-to-make-a-simple-dynamic-proxy-in-c-sharp) – CodeNotFound Jun 01 '17 at 18:41
-
1Another option: Castle's DynamicProxy2. – Jun 01 '17 at 21:01
-
@Amy : Thank you! I have checked Castle's Dynamic proxy. I managed to use the Dynamic object and extend a class with new properties. However, the result is still a dynamic object. How is EF managing to create a class named something like System.Data.Entity.DynamicProxies.EntityName_LOG_GUID_FOLLOWS? – Midas Jun 02 '17 at 16:41
-
1It creates a dynamic module that contains types. (Note the distinction: the *module* is dynamic, which contains types you create at runtime, but those types aren't 'dynamic types'). Something similar to [this](https://stackoverflow.com/questions/18467235/creating-dynamic-type-from-typebuilder-with-a-base-class-and-additional-fields-g). I've fiddled with that before, it's quite painful to work with, but doable. You can search the EF source code for "TypeBuilder", should return some hits. – Jun 02 '17 at 16:51
-
1Even if you don't follow the `TypeBuilder` approach, I consider it useful to learn. IMO, it will help expand your knowledge of how C# works under the covers. I proposed DynamicProxy2 simply because its easier and more useful, particularly if you use Dependency Injection. IIRC (and i could be wrong on this) DynamicProxy2 uses `TypeBuilder` internally. – Jun 02 '17 at 16:58
-
@Amy Thank you! This helped a bit to narrow my search for a solution. – Midas Jun 02 '17 at 19:13