Demorepo:
https://github.com/gabbersepp/csharp-dynamic-replace-class
How to use:
- Checkout
- Compile
- Delete TestLib.dll & TestLib.pdb from console/bin/Debug
- Execute console.exe through cmd
Old SO post:
Replace existing class definition at runtime with newly created type
Given:
A class in a lib:
namespace Test.TestLib
{
public class Class1
{
}
}
And a second class which creates an instance of it:
namespace console
{
public class AnotherClass
{
public void Create()
{
new Class1();
}
}
}
And a console app that calls create
:
static void Main(string[] args)
{
//...
new AnotherClass().Create();
}
Please keep in mind that only Class1
is in an extra lib. The other two classes are in the same.
What I want to do:
Replace the Assembly at runtime:
AssemblyName dynamicAssemblyName = new AssemblyName("TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
dynamicAssembly =
AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
var dynamicModule = dynamicAssembly.DefineDynamicModule("TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
But I want not provide the type at this time. Instead I use:
AppDomain.CurrentDomain.TypeResolve += CurrentDomain_TypeResolve;
private static Assembly CurrentDomain_TypeResolve(object sender, ResolveEventArgs args)
{
Console.WriteLine("resolve type");
if (args.Name.Contains("TestLib"))
{
dynamicModule.DefineType("Test.TestLib.Class1", TypeAttributes.Class | TypeAttributes.Public).CreateType();
return dynamicAssembly;
}
return null;
}
Problem:
The event is not called when the line new AnotherClass().Create();
is executed. Instead an exception is thrown:
System.TypeLoadException: Der Typ "Test.TestLib.Class1" in der Assembly "TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" konnte nicht geladen werden
something like:
System.TypeLoadException: The type "Test.TestLib.Class1" in the assembly "TestLib, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null" could not be loaded
Please have a look into the repo for a full example.
Aucun commentaire:
Enregistrer un commentaire