在Startup.cs .net core 2.1中加载程序集

我有一个名为nuqkgs的文件夹中的块包,在项目启动时我想将这些包(有dll)加载到项目中以便在运行时使用。

我使用以下代码加载它们,当我调试时,我可以看到信息,并且找到并打开了dll,但是当它们应该被使用时,我得到了无法找到dll的错误,我可以看到解决方案尝试在bin文件夹中查找它们(它们位于solution / nuqkgs /)

我不想在任何文件中注册包我只是希望能够将一个块包放入nuqkgs文件夹并自动注册

任何想法或任何人在核心2.1中做到这一点?

这是我的startup.cs:

public void ConfigureServices(IServiceCollection services) { services.Configure(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); IList components = new List(); foreach (string file in Directory.EnumerateFiles(@"C:\Users\myName\source\repos\core2.1test\core2.1test\nuqkgs\", "*.nupkg", SearchOption.AllDirectories)) { using (ZipArchive nuget = ZipFile.Open(file, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry entry in nuget.Entries) { if (entry.Name.Contains(".dll")) { using (BinaryReader reader = new BinaryReader(entry.Open())) { components.Add(Assembly.Load(reader.ReadBytes((int)entry.Length))); } } } } } services.AddMvc() .ConfigureApplicationPartManager(apm => { foreach (var c in components) { var part = new AssemblyPart(c); var des = part.Assembly.Location.ToString(); apm.ApplicationParts.Add(part); } }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } 

AssemblyLoadContext的文档中所述, Assembly.Load(byte[])将程序集加载到新的未命名加载上下文中,而AssemblyLoadContext (默认值除外)当前无法解析依赖项。 这可能就是为什么你的部件不起作用的原因。 尝试使用AssemblyLoadContext.Default.LoadFromStream而不是Assembly.Load(byte[])

我让它工作,我现在使用它的方式:

  1. – 打开nugget foreach DLL,然后将dll写入磁盘上的文件。
  2. – 在内存流中打开文件并将其读入内存,然后可以在我的应用程序中使用它。

作为第2步的替代,您可以使用:AssemblyLoadContext.Default.LoadFromAssemblyPath(createPathSource);

这样你在解决方案中使用它时就会遇到dll文件

  public void ConfigureServices(IServiceCollection services) { IList components = new List(); foreach (string file in Directory.EnumerateFiles(@"C:\Users\userName\source\repos\core2.1test\core2.1test\nuqkgs\", "*.nupkg", SearchOption.AllDirectories)) { using (ZipArchive nuget = ZipFile.Open(file, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry entry in nuget.Entries) { if (entry.Name.Contains(".dll")) { string createPathSource = @"C:\Users\userName\source\repos\core2.1test\core2.1test\nuqkgs\"+ entry.Name; using (BinaryReader reader = new BinaryReader(entry.Open())) { //step 1 using (FileStream fsNew = new FileStream(createPathSource, FileMode.Create, FileAccess.Write)) { fsNew.Write(reader.ReadBytes((int)entry.Length), 0, (int)entry.Length); } //step 2 using (FileStream readStream = File.Open(createPathSource, FileMode.Open)) { var assempbly = AssemblyLoadContext.Default.LoadFromStream(readStream); components.Add(assempbly); } } } } } } services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMvc() .ConfigureApplicationPartManager(apm => { foreach (var c in components) { var part = new AssemblyPart(c); apm.ApplicationParts.Add(part); } }); }