本教程使用自定义 ALC (AssemblyLoadContext) 仅加载一个不依赖于其他组件的插件程序集。
在您的情况下,自定义 ALC 会加载插件并解决所有依赖项。
In the 定制ALC https://learn.microsoft.com/en-us/dotnet/core/tutorials/creating-app-with-plugin-support#load-plugins,你注意到它使用程序集依赖解析器 https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblydependencyresolver?view=netcore-3.1(.Net Core 3.0+ 中的新类)
AssemblyDependencyResolver 类使应用程序开发人员能够更轻松地与自定义 System.Runtime.Loader.AssemblyLoadContext 实例结合开发插件架构,以隔离插件并允许插件加载依赖项。
重要提示:
插件应包括ExcludeAssets=runtime
对于共享程序集的项目引用,ref https://github.com/dotnet/docs/issues/15811.
例如,如果项目Common
包含接口“IContract”并由主机应用程序和插件项目引用,请添加引用,如下所示:
<!-- in the plugin project -->
<ItemGroup>
<ProjectReference Include="..\IContract\Common.csproj">
<Private>false</Private>
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
<ProjectReference Include="..\MyLibObjectsLib\MyLibObjectsLib.csproj" />
</ItemGroup>
此代码用于加载插件:
string pluginPath = @"path/to/MyContract.Plugin.dll";
var assembly = new PluginLoadContext(pluginPath).LoadFromAssemblyPath(pluginPath);
var type = assembly.GetTypes()
.FirstOrDefault(t => t.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
if (type != null) {
var instance = (IContract)Activator.CreateInstance(type);
var ret = instance.Execute();
}
我将您的插件模拟为standard2.0库,并且插件引用OLEDB nuget包,并且插件加载没有错误。