2017-02-04 43 views
0

我目前正在實現一個基本的解決方案,通過反射將服務加載到Asp.Net核心,而不必傳遞每一種類型。 有一些迴旋的房間,我創建了一個靜態輔助使用新的核心反射類型返回我的組件類型:Asp.Net核心:反映Asp.Net程序集拋出異常

internal static class ReflectionTypeHelper 
{ 
    private static readonly Assembly _currentAssembly = typeof(ServiceContainerInitializer).GetTypeInfo().Assembly; 

    internal static IReadOnlyCollection<Type> ScanAssembliesForTypes(Func<Type, bool> predicate) 
    { 
     var result = new List<Type>(); 
     var appAssemblies = GetApplicationAssemblies(); 

     foreach (var ass in appAssemblies) 
     { 
      var typesFromAssembly = ass.GetTypes().Where(predicate); 
      result.AddRange(typesFromAssembly); 
     } 

     return result; 
    } 

    private static IEnumerable<Assembly> GetApplicationAssemblies() 
    { 
     var consideredFileExtensions = new[] 
     { 
      ".dll", 
      ".exe" 
     }; 

     var result = new List<Assembly>(); 
     var namespaceStartingPart = GetNamespaceStartingPart(); 

     var assemblyPath = GetPath(); 
     IEnumerable<string> assemblyFiles = Directory.GetFiles(assemblyPath); 

     var fileInfos = assemblyFiles.Select(f => new FileInfo(f)); 
     fileInfos = fileInfos.Where(f => f.Name.StartsWith(namespaceStartingPart) && consideredFileExtensions.Contains(f.Extension.ToLower())); 

     // Net.Core can't load the Services for some reason, so we exclude it at the moment 
     //fileInfos = fileInfos.Where(f => f.Name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) == -1); 

     foreach (var fi in fileInfos) 
     { 
      var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(fi.FullName); 
      result.Add(assembly); 
     } 

     return result; 
    } 

    private static string GetNamespaceStartingPart() 
    { 
     var fullNamespace = _currentAssembly.FullName; 
     var splittedNamespace = fullNamespace.Split('.'); 

     var result = string.Concat(splittedNamespace[0], ".", splittedNamespace[1]); 
     return result; 
    } 

    private static string GetPath() 
    { 
     var codeBase = _currentAssembly.CodeBase; 
     var uri = new UriBuilder(codeBase); 
     var result = Uri.UnescapeDataString(uri.Path); 
     result = Path.GetDirectoryName(result); 

     return result; 
    } 
} 

正如你可以在代碼註釋可能看到,我無法加載從「ASP.NET核心Web應用程序(.Net Core)」 - 項目模板中創建的「服務」 - 裝配。

不幸的是,除了是很普通的

無法加載文件或程序集 'Argusnet.Pis.Services, 版本= 1.0.0.0,文化=中立,公鑰=空'。

此外,該文件是按預期方式。 我的確在GitHub-Issues上發現了關於這個主題的一些提示,但它們都在發佈候選版本中解決。

有趣的是,所有其他程序集按照您的預期工作,所以必須有關於此程序集類型的特定內容?

編輯:異常的截圖: enter image description here

+0

您確定您發佈的錯誤消息已完成嗎?一般情況下'無法加載文件或程序集......'異常還會有第二部分指出更具體的原因。 –

+0

感謝您的輸入,我重新檢查了它並添加了屏幕截圖。信息本身沒有內容不足,也沒有更多的文字,足夠有趣。 –

回答

0

一個爲什麼它無法加載可能是在編譯過程中選擇了目標處理器架構不匹配的原因。 Argusnet.Pis.Services可能使用x86配置進行編譯,嘗試加載的客戶端應用程序可能在編譯期間使用x64選項構建,或者以其他方式構建。確保兩個項目在構建之前都具有相同的選項(x86或x64)。否則,請嘗試使用Any CPU選項構建它們。

+0

感謝您的提示,但它們全部構建爲任何CPU。讓我們希望這是團隊意識到的事情,有時我們可能會得到解決。 –