2013-03-02 49 views
3

如何獲取C#中父程序集中引用的列表。我正在考慮加載到另一個程序中的DLL,並且驅動程序需要在反射和序列化中使用某些父組件引用。到目前爲止,我還沒有嘗試過任何事情,因爲我不知道從哪裏開始。如何動態加載C#中父程序集中的引用

+1

你是什麼意思*親組件*?你的意思是調用程序集? – 2013-03-02 13:15:39

+0

如果你考慮插件系統,你應該考慮MEF。 – IamStalker 2013-03-02 13:15:52

+0

也許DLL會比驅動程序更好地描述它。它實際上是程序可以加載和使用的常規DLL。 – 2013-03-02 13:17:05

回答

4

這是很經典的反射問題,當你需要加載一個組件和組件包含引用,這是不參考調用程序集。

基本上,您應該將程序集加載到單獨的應用程序域中。

例如,你有一個項目proxyDomain行一類的proxyType:

public class ProxyType : MarshalByRefObject 
{ 
    public void DoSomeStuff(string assemblyPath) 
    { 
     var someStuffAssembly = Assembly.LoadFrom(assemblyPath); 

     //Do whatever you need with the loaded assembly, e.g.: 
     var someStuffType = assembly.GetExportedTypes() 
      .First(t => t.Name == "SomeStuffType"); 
     var someStuffObject = Activator.CreateInstance(someStuffType); 

     someStuffType.GetMethod("SomeStuffMethod").Invoke(someStuffObject, null); 
    } 
} 

而在你調用項目,它包含proxyDomain行的引用,您需要加載該程序集,執行DoSomeStuff和卸載程序集資源:

public class SomeStuffCaller 
{ 
    public void CallDoSomeStuff(string assemblyPath) 
    { 
     AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; 
     //Path to the directory, containing the assembly 
     setup.ApplicationBase = "..."; 
     //List of directories where your private references are located 
     setup.PrivateBinPath = "..."; 
     setup.ShadowCopyFiles = "true"; 

     var reflectionDomain = AppDomain.CreateDomain("ProxyDomain", null, setup); 

     //You should specify the ProxyDomain assembly full name 
     //You can also utilize CreateInstanceFromAndUnwrap here: 
     var proxyType = (ProxyType)reflectionDomain.CreateInstanceAndUnwrap(
      "ProxyDomain", 
      "ProxyType"); 

     proxyType.DoSomeStuff(assemblyPath); 

     AppDomain.Unload(reflectionDomain); 
    } 
} 
相關問題