簡體   English   中英

在不知道類型的情況下將程序集從文件加載到自定義AppDomain

[英]Load assemblies from file to custom AppDomain without knowing type

我需要在單獨的AppDomain加載幾個.dll文件,對它們進行一些操作,然后卸載AppDomain。 我可以通過CreateInstanseFrom做到這一點,但我需要知道類型的名稱。

如果我得到給定程序集中的所有類型,則可以過濾掉我的。

我可以通過反射獲得所有類型,但這僅適用於當前的AppDomain,對嗎? 首先在當前域中加載文件,獲取類型並將其加載到自定義域中是沒有用的。

有沒有一種方法可以將程序集從文件加載到自定義應用程序域?

不要嘗試使用CreateInstanceFrom / CreateInstanceFromAndUnwrap調用中的目標程序集中的某個類,而要使用自己的類。 您可以在appdomain中創建該知名類,然后調用一個知名方法。 在該眾所周知的方法中,處理程序集。

// This class will be created inside your temporary appdomain.
class MyClass : MarshalByRefObject
{
    // This call will be executed inside your temporary appdomain.
    void ProcessAssemblies(string[] assemblyPaths)
    {
        // the assemblies are processed here
        foreach (var assemblyPath in assemblyPaths)
        {
            var asm = Assembly.LoadFrom(assemblyPath);
            ...
        }
    }
}

像這樣使用它來處理程序集:

string[] assembliesToProcess = ...;

// create the temporary appdomain
var appDomain = AppDomain.CreateDomain(...);
try
{
    // create a MyClass instance within the temporary appdomain
    var o = (MyClass) appDomain.CreateInstanceFromAndUnwrap(
        typeof(MyClass).Assembly.Location,
        typeof(MyClass).FullName);

    // call into the temporary appdomain to process the assemblies
    o.ProcessAssemblies(assembliesToProcess);
}
finally
{
    // unload the temporary appdomain
    AppDomain.Unload(appDomain);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM