2017-02-04 125 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。让我们希望这是团队意识到的事情,有时我们可能会得到解决。 –