如何在C#中获取父程序集中的引用列表。我正在考虑将DLL加载到另一个程序中,并且驱动程序需要在反射和序列化中使用一些父程序集引用。到目前为止,我还没有尝试任何东西,因为我不知道从哪里开始。
答案 0 :(得分:4)
当您需要加载程序集并且程序集包含未引用调用程序集的引用时,这是非常经典的反射问题。
基本上,您应该将程序集加载到单独的应用程序域中。
例如,您有一个具有ProxyType类的项目ProxyDomain: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);
}
}