.net - Is it possible to add a type to an existing module in c#? -


i have situation need dynamically add types application. basically, what's going on want use ef6, still run dynamic queries against database , return dictionary of key/value pairs. (legacy code, don't ask)

i can achieve calling context.database.sqlquery , passing dynamically loaded type, create on fly.

i'm using method found online so.

private static typebuilder createtypebuilder(     string assemblyname, string modulename, string typename) {      typebuilder typebuilder = appdomain.currentdomain         .definedynamicassembly(new assemblyname(assemblyname), assemblybuilderaccess.run)         .definedynamicmodule(modulename)         .definetype(typename, typeattributes.public);     typebuilder.definedefaultconstructor(methodattributes.public);     return typebuilder; } 

which works great, every time add new type (which may often) loads new dynamic assembly. result in hundreds of assemblies used once.

i'm able pull down dynamic assembly using following statement:

var loadedassembly = appdomain.currentdomain.getassemblies().firstordefault(ex => ex.getname().name == assemblyname); 

i'm able dynamic module using following:

var loadedmodule = loadedassembly.getmodules().firstordefault(ex => ex.scopename == modulename); 

but that's far get, can't add types past point.

am barking wrong tree?

the key part line:

.definedynamicassembly(new assemblyname(assemblyname), assemblybuilderaccess.run) .definedynamicmodule(modulename) 

that method returns instance of dynamic assembly , module. instead of calling definedynamicassembly , definedynamicmodule every time need new type, create dynamic assembly , module once, call definetype on module each type need. perhaps this:

internal static class dyanamictypebuilder {     private static readonly assemblybuilder _assembly;     private static readonly modulebuilder _module;     private static readonly object _syncblk = new object();      static dyanamictypebuilder()     {         _assembly = appdomain.currentdomain.definedynamicassembly(new assemblyname("mydyanmicassembly"), assemblybuilderaccess.run);         _module = _assembly.definedynamicmodule("mydynamicmodule");     }      private static typebuilder createtypebuilder(string typename)     {         lock (_syncblk)         {             var typebuilder = _module.definetype(typename, typeattributes.public);             typebuilder.definedefaultconstructor(methodattributes.public);             return typebuilder;         }     } } 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -