Using .NET Core CLI, add a reference to a local DL

2019-04-17 09:25发布

问题:

I would like to know how to reference a local, unsigned CLR 4.0 assembly, when building a new Console application using the .NET Core tools and only targeting the .NET 4.5.1 framework.

I did the following on a Windows 10 machine:

  1. Create a new MyLibrary.cs with the following code:
using System;
namespace MyNamespace
{
  public class MyLibrary
  {
    public static void SayHi()
    {
      Console.WriteLine("Hi");
    }
  }
}
  1. Compile the above with csc /t:library MyLibrary.cs.

  2. Create a new folder and a .NET Core project.

mkdir MyConsoleApp
cd MyConsoleApp
dotnet new
  1. Edit the auto-generated project.json file to target .NET 4.5.1.
{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "net451" : { } 
  }
}
  1. Test that the project builds and runs. It does.
dotnet restore
dotnet build
bin\Debug\net451\MyConsoleApp.exe
  1. Edit Program.cs to call code in MyLibrary.dll.
public static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
    MyNamespace.MyLibrary.SayHi();
}

And this is where I am stuck.

Where do I place my DLL and what do I put in the project.json so that I can call code in my assembly?

回答1:

The legacy DLL must be wrapped in a nuget package. I have never created a nuget package before. Here is how I did it in this case:

1. Prepare to create a nuget package for the legacy DLL:

cd..
mkdir lib\net40
move MyLibrary.dll lib\net40
nuget spec -AssemblyPath lib\net40\MyLibrary.dll
// which generates a MyLibrary.dll.nuspec XML file.

2. Fill in or delete fields in the nuspec file:

<?xml version="1.0"?>
<package >
  <metadata>
    <id>MyLibrary.dll</id>
    <version>1.0.0</version>
    <authors>Wallace Kelly</authors>
    <description>My test library.</description>
  </metadata>
</package>

3. Pack the nuget package and move it into the nuget folder structure:

nuget pack MyLibrary.nuspec -OutputDirectory lib\net40
// which generates a MyLibrary.dll.1.0.0.nupkg

4. Create a new nuget-source folder:

nuget init lib nuget-source

5. In the project folder (e.g, MyConsoleApp), create a new nuget.config file with the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>

6. Add your local nuget-source folder to the list of nuget's sources:

nuget sources add -Name "Local Source" -Source "c:\temp\dotnet-core-test\nuget-source" -configfile nuget.config

In the project.json file, add a dependency to the legacy DLL.

"dependencies": {
  "MyLibrary.dll": "1.0.0"
}, 

7. At this point, you should be able to restore, build, and run the project.

dotnet restore
dotnet build
dotnet run

HT: Thanks to @michael-kennedy for helping me work this out.



标签: .net-core