I have looked every resources in the net and I could not find any answer!
I want to know if its possible to override or recompile a function in the parent application by Dynamic Compilation, by using C# CSharpCodeProvider.
I have provide a simple pseudocode as shown below.
the Test class is what I want to override or recompile.
class Test
{
public virtual void Testing1()
{
Console.WriteLine("Method1");
}
}
What actually I want to do is to dynamically compile the 'source' and override the Test.Testing1. I think my idea has many problems, please guide me.
source= @"
class Test
{
public override void Testing1()
{
Console.WriteLine(""Method2"");
}
}
"
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
};
var assemblies = typeof(Program).Assembly.GetReferencedAssemblies();
var assemblyLocations = assemblies.Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Location).ToList();
assemblyLocations.Add(typeof(Program).Assembly.Location);
compilerParams.ReferencedAssemblies.AddRange(assemblyLocations.ToArray());
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
As conclusion, Lets say if I execute the below code before dynamic compilation, the output would be "Method 1".
Test test = new Test();
test.Testing1();
and if I execute the same code after compilation, I want to get "Method 2" as output.