简体   繁体   中英

Dynamically loading ASP .Net Core assemblies into regular .Net Core assemblies

I have a project which targets ASP.Net Core 3.1, as such:

<Project Sdk="Microsoft.NET.Sdk.Web">

I have another project (which targets.Net Core 3.1 and does not have a framework reference to ASP.Net Core) which needs to dynamically load the above's assembly:

var assembly = Assembly.LoadFrom(filePath);
var references = assembly.GetExportedTypes();

This fails on the second line with following exception:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.'

I don't recall ever having this issue when the assembly being loaded referenced normal assemblies, but for some reason it fails with ASP. This succeeds if the project doing the loading has a framework reference to ASP.Net Core.

How can I load ASP.Net Core assemblies into regular.Net Core assemblies?

Quick demonstration


Use **PreserveCompilationReferences** property in your *.csproj to output Microsoft.AspNetCore.Mvc.Core dll (and all framework reference dll's) into your output folder.:

https://docs.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#preservecompilationreferences

Remember to also load assemblies that yours project reference to so it will be able to use them. You can do it by writing your own automatic assembly loader of all dll's in same folder isntead of single one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM