Warm tip: This article is reproduced from stackoverflow.com, please click
.net c# nuget package rider

How to reference NuGet packages?

发布于 2020-04-13 09:40:41

I'm a newcomer to .NET world, and at this point I'm super confused about the packages, references and how to reference them in my c# project.

I have 3 project in my solution:

  • DataAccess - which contains the logic for accessing data, the mapping between DTOs and entities, etc.,
  • DataAccessTest - contains unit tests for DataAccess project,
  • Service - wraps the DataAccess project into a Windows service.

Now, DataAccess project references AutoMapper (among others) to help with data transformation. It's included in <PackageReference /> element in the csproj file. It seems to be working fine when I'm doing dotnet restore, however dotnet build fails when trying to resolve the namespaces! The same goes for JetBrains Rider - it doesn't find the namespaces until I explicitly reference them in <Reference>!

Not sure if related, but the same goes for the dependent projects. For example, DataAccessTest references the DataAccess project - so that the test will run. However, it still requires adding the transitive dependencies (for example AutoMapper), on top of the project reference.

Is this the intended behavior? Do you need to keep both <PackageReference> and <Reference> for project to compile correctly?

Questioner
mhaligowski
Viewed
65
RudolfJan 2020-02-11 01:28

You need to install Nuget packages for each project that references methods in that package. So, if only your DataAccess project requires AutoMapper, it should be sufficient to add the Nuget package to that project. The solution is not much more than a wrapper around a bunch of projects. You should be able to publish a project separately. The project will take care of its own dependencies. It is hard to find out what goes wqrong. It may be helpful if you create a small testproject, e.g. create an empty console project and a DataAccess Library. Then you add a Nuget package to your DataAccess library and copile all stuff. In this way you can try to find out what is goning wrong. Make sure to install the Nuget Packages for the correct project (I got this wrong several times before I discovered how it really worked).