Is there any way to create dynamic types at runtime without having them permanently in the app domain?
My current understanding of dynamically generated types is this:
If you generate a type via CodeDom and load it into an AppDomain, ther开发者_如何转开发e is no way to unload that type (i.e. Assembly.Unload(...)
doesn't exists) without destroying the AppDomain as a whole.
Are there any other ideas on how to create custom types at runtime?
Can the C# 4.0 dynamic
keyword be used somehow magically? Could the .NET 4 ExpandoObject
be utilised is some lovely way?
Could anonymous types and the dynamic keyword be combined with some technical wizardry?! It feels like we have the tools scattered that might achieve something useful. But I could be wrong.
Once an assembly or type has been loaded into the AppDomain, it's there until the AppDomain is torn down, period, no exceptions.
That's why CodeDom is pure evil when used in any kind of bulk. It's a guaranteed memory leak and performance problem. EVERY compile with CodeDom generates a new assembly. I think you have a few of options:
Run a sandboxed AppDomain for your dynamic types.
Run your primary AppDomain in an environment where recycles and pooling are acceptable. Obviously in a client application, this is not possible, but if you're running in ASP .NET you can add code that monitors the number of Assemblies loaded in your AppDomain and requests a recycle when that number reaches a critical point. Then just have IIS pool your web application and you still have high availability, since you have multiple AppDomains running at once.
Use TypeBuilder and Reflection.Emit. This lets you use one dynamic assembly for all of your dynamically generated types.
If you want to dynamically generate C# style code like you can with CodeDom, you can still use this in conjunction with TypeBuilder, so your dynamic C# code gets compiled to a TypeBuilder in a dynamic assembly, instead of to a new assembly every time. To do this you can use MCS (Mono compiler service). You can pass it C# formatted classes and with a little tweaking, you can have it compile your code to a single dynamic assembly. See Mono Compiler as a Service (MCS)
精彩评论