2017-06-10 44 views
0

我從VS2008在vs2017移植一個.net 3.5控制檯應用程序爲.NET核心控制檯應用程序(目標框架netcoreapp1.1)。未能加載文件或asssembly

該程序通過在給定目錄中查找.dlls並將其作爲程序集加載來執行一些插件加載。

我已經重建了插件,netstandard1.6庫。誠然,我的核心,框架和標準之間的差別有點困惑。

我使用System.Runtime.Loader(V4.3.0)NuGet包和下面的代碼從給定的路徑嘗試加載組件:

public static Assembly LoadAssemblyFromPath(string path) 
{ 
    AssemblyLoadContext.Default.Resolving += (context, name) => 
    { 
     // avoid loading *.resources dlls, because of: https://github.com/dotnet/coreclr/issues/8416 
     if (name.Name.EndsWith("resources")) 
      return null; 

     string[] foundDlls = 
      Directory.GetFileSystemEntries(new FileInfo(path).FullName, name.Name + ".dll", SearchOption.AllDirectories); 

     return foundDlls.Any() ? context.LoadFromAssemblyPath(foundDlls[0]) : context.LoadFromAssemblyName(name); 
    }; 

    return AssemblyLoadContext.Default.LoadFromAssemblyPath(path); 
} 

我驗證過的路徑參數是正確的和該文件存在,但我仍然得到一個「無法加載文件或程序集」異常。決不會提出解決事件。

任何人都可以提供任何見解我做錯了什麼?

+0

是你還加載的.Net核心的dll的dll?核心應用程序無法加載爲.net框架構建的DLL,它只能加載爲.net core或.net標準構建的dll。 –

+0

如何確定的?插件DLL都是目標框架netstandard1.6 – Vesuvian

+0

就像一個說明,因爲你在談論插件;你有沒有考慮過使用MEF?這是一個關於它的博客:https://weblogs.asp.net/ricardoperes/using-mef-in-net-core – Silvermind

回答

0

我最終使用下列內容:

public static Assembly LoadAssemblyFromPath(string path) 
    { 
     string fileNameWithOutExtension = Path.GetFileNameWithoutExtension(path); 

     bool inCompileLibraries = DependencyContext.Default.CompileLibraries.Any(l => l.Name.Equals(fileNameWithOutExtension, StringComparison.OrdinalIgnoreCase)); 
     bool inRuntimeLibraries = DependencyContext.Default.RuntimeLibraries.Any(l => l.Name.Equals(fileNameWithOutExtension, StringComparison.OrdinalIgnoreCase)); 

     return inCompileLibraries || inRuntimeLibraries 
      ? Assembly.Load(new AssemblyName(fileNameWithOutExtension)) 
      : AssemblyLoadContext.Default.LoadFromAssemblyPath(path); 
    }