2012-04-25 50 views
4

如果我使用加载组件到应用程序域

Assembly assembly = Assembly.LoadFrom(file); 

后来又尝试使用的文件,我得到一个异常,说明该文件正在使用中。

我需要将它加载到一个新的appdomain。

所有我似乎找到的是如何在装配中创建实例的示例, 是否有加载整个装配的方法

什么,我需要的是:

(1) load the assembly into a new AppDomain from a file . 
(2) extract an embedded resource (xml file) from the Dll . 
(3) extract a type of class which implements an interface (which i know the interface type) . 
(4) unload the entire appdomain in order to free the file . 

2-4是没有问题的

我似乎无法找到如何将程序集加载到一个新的AppDomin,只有 创建实例的例子,这给了我在Dll中的类的一个例子。

我需要整个事情。

像这样的问题:创建实例的另一个例子。

Loading DLLs into a separate AppDomain

+0

有你看着http://msdn.microsoft.com/en-us被initilised /library/25y1ya39.aspx ?? – rt2800 2012-04-25 12:47:37

+1

也许这个答案可能对你有帮助吗? http://stackoverflow.com/a/225355/747511 – 2012-04-25 12:58:29

回答

2

最基本的多域的情况是

static void Main() 
{ 
    AppDomain newDomain = AppDomain.CreateDomain("New Domain"); 
    newDomain.ExecuteAssembly("file.exe"); 
    AppDomain.Unload(newDomain); 
} 

在一个单独的域调用ExecuteAssembly是convienient但不提供与域名本身交互的能力。它还要求目标程序集是一个可执行文件,并强制调用者进入一个入口点。为了整合一些灵活性,你也可以传递一个字符串或参数给.exe。

我希望这会有所帮助。

扩展:尝试像那么下面

AppDomainSetup setup = new AppDomainSetup(); 
setup.AppDomainInitializer = new AppDomainInitializer(ConfigureAppDomain); 
setup.AppDomainInitializerArguments = new string[] { unknownAppPath }; 
AppDomain testDomain = AppDomain.CreateDomain("test", AppDomain.CurrentDomain.Evidence, setup); 
AppDomain.Unload(testDomain); 
File.Delete(unknownAppPath); 

其中AppDomain可以如下

public static void ConfigureAppDomain(string[] args) 
{ 
    string unknownAppPath = args[0]; 
    AppDomain.CurrentDomain.DoCallBack(delegate() 
    { 
     //check that the new assembly is signed with the same public key 
     Assembly unknownAsm = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(unknownAppPath)); 

     //get the new assembly public key 
     byte[] unknownKeyBytes = unknownAsm.GetName().GetPublicKey(); 
     string unknownKeyStr = BitConverter.ToString(unknownKeyBytes); 

     //get the current public key 
     Assembly asm = Assembly.GetExecutingAssembly(); 
     AssemblyName aname = asm.GetName(); 
     byte[] pubKey = aname.GetPublicKey(); 
     string hexKeyStr = BitConverter.ToString(pubKey); 
     if (hexKeyStr == unknownKeyStr) 
     { 
      //keys match so execute a method 
      Type classType = unknownAsm.GetType("namespace.classname"); 
      classType.InvokeMember("MethodNameToInvoke", BindingFlags.InvokeMethod, null, null, null); 
     } 
    }); 
} 
+0

这是你所需要的? – MoonKnight 2012-04-25 13:01:10

相关问题