在 .NET Core 项目中引用外部 DLL

Reference external DLL in .NET Core project

我有自己的 .dll 文件,我曾经在 nodejs 中与 Edge.js 一起使用, 我现在正尝试将它与 dot net core 应用程序一起使用,但没有发现 where/no 如何访问它或定义它。

有没有像

"files":
{
    "":"MyLibrary.dll"
}

或喜欢

using MyLibraryFile.dll

以便我可以使用其中的功能?

我的汇编文件结构是: MyLibraryFile.dll

namespace MyLibrary
{
    public class Inventory
    {
        public async Task<object> Invoke(object input)
    {
}

using MyLbrary;using MyLbraryFile; 都不起作用

我需要将其与 MS Code 编辑器一起使用,而不是与 MS Studio 一起使用。 并且不想使用 NuGet package

  • .NET Core 只能通过 Nuget 使用依赖项。 How do I import a .NET Core project to another .NET Core project in Visual Studio? 相关。

  • 使用 VS Code,您可以添加对修改 project.json 文件的 Nuget 包的引用。查看 "dependencies" 部分

    An object that defines the package dependencies of the project, each key of this object is the name of a package and each value contains versioning information. For more information, see the Dependency resolution article on the NuGet documentation site.

    更新:从 .NET Core 1.1 开始,您需要通过添加 <PackageReference> 部分来修改 .csproj 文件。例如:

    <ItemGroup>
     <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
     <PackageReference Include="MySql.Data" Version="6.9.9" />
    </ItemGroup>
    
  • 在 C# 中 using 添加命名空间,而不是对程序集的引用。


您可以通过以下代码添加一个dll:

[DllImport("MyLbraryFile.dll", SetLastError = true, CharSet = CharSet.Auto)]

你所要做的就是将 dll 放在同一目录中。

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(v=vs.110).aspx

.Net Core 2 支持直接引用外部 .dll(例如 Net Standard 库、经典 .Net Framework 库)。您可以通过 Visual Studio UI 来完成:右键单击 Dependencies->Add reference->Browse 和 select 您的外部 .dll.

或者,您可以编辑 .csproj 文件:

<ItemGroup>
  <Reference Include="MyAssembly">
    <HintPath>path\to\MyAssembly.dll</HintPath>
  </Reference>
</ItemGroup>

您可能会遇到以下错误:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly

然后只需删除 \bin 文件夹并重建项目。它应该可以解决问题。

怎么可能

Net Core 2.0 支持 .Net Standard 2.0Net Standard 2.0 提供了一个 compatibility mode 来连接 .Net Core(.Net Standard) 和 .NET Framework。它可以重定向引用,例如从 mscorlib.dll(Net.Framework) 到 System.Int32System.Runtime.dll(Net.Core)。但是,即使您的网络核心应用程序在依赖外部 dll 的情况下成功编译,如果外部库使用了任何 API 而 .Net Standard 没有,您在运行时仍然可能会遇到兼容性问题。

在 Visual Studio 导航解决方案资源管理器中:

  1. 在引用中右击->添加引用
  2. 在文件资源管理器中查找您的 dll,选择并单击接受按钮
  3. 重新编译。

VS Add dll to project