Mega Code Archive

 
Categories / C# / Reflection
 

AppDomain AssemblyResolve Event

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; public class MyType {     public MyType()     {         Console.WriteLine();         Console.WriteLine("MyType instantiated!");     } } class Test {     public static void Main()     {         AppDomain currentDomain = AppDomain.CurrentDomain;         InstantiateMyTypeFail(currentDomain);         currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);         InstantiateMyTypeFail(currentDomain);         InstantiateMyTypeSucceed(currentDomain);     }     private static void InstantiateMyTypeFail(AppDomain domain)     {         try         {             domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");         }         catch (Exception e)         {             Console.WriteLine();             Console.WriteLine(e.Message);         }     }     private static void InstantiateMyTypeSucceed(AppDomain domain)     {         try         {             string asmname = Assembly.GetCallingAssembly().FullName;             domain.CreateInstance(asmname, "MyType");         }         catch (Exception e)         {             Console.WriteLine();             Console.WriteLine(e.Message);         }     }     private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)     {         Console.WriteLine("Resolving...");         return typeof(MyType).Assembly;     } }