.net 4.0 -如何在c#中动态加载父程序集中的引用
本文关键字:程序 加载 程序集 集中 引用 动态 net | 更新日期: 2023-09-27 18:01:55
如何在c#中获得父程序集中的引用列表?我正在考虑加载到另一个程序中的DLL,并且驱动程序需要在反射和序列化中使用一些父程序集引用。到目前为止,我还没有尝试过任何东西,因为我不确定从哪里开始。
这是一个非常经典的反射问题,当您需要加载程序集并且程序集包含引用时,这些引用不是调用程序集的引用。
基本上,您应该在单独的应用程序域中加载程序集。。,你有一个项目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);
}
}