How to include a library in .NET Core 2.0

MrMid picture MrMid · Aug 20, 2017 · Viewed 20.2k times · Source

I don't know much about .NET yet, so I guess I'm missing something obvious.

I created a library (targeted as a DLL file, set for .NET standard 2.0), packaged it both as a DLL file and as a NuGet package. Now I want to use the library in another project, on ASP.NET Core 2.0. How should I do it?

I am currently on a Linux VM, so I use Visual Studio Code, and therefore I would prefer some solution without using the full Visual Studio. I tried some solutions using the full Visual Studio, but that didn't work for me, because I haven't found a reference explorer anywhere.

Answer

areller picture areller · Aug 20, 2017

You would have to reference your library in the .csproj file:

Enter image description here

An empty .csproj file would look like this:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

Now, you can have two types of references:

Project Reference - You have a project that serves as a class library in your solution and you want to reference it directly:

<ProjectReference Include="..\..\src\mylib.csproj" />

Package Reference - You have a link to a NuGet package:

<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="1.1.2" />

Inside your .csproj file, the references should be inside an "ItemGroup" block, and each reference type should have its own "ItemGroup".

Here's an example of a .csproj file with some package references and some project references:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.1.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\src\mylib.csproj" />
    <ProjectReference Include="..\..\src\mylib2.csproj" />
  </ItemGroup>
</Project>