Use a .nuspec file/script to automatically install nuget packages into a new project

前端 未结 2 1368
长情又很酷
长情又很酷 2021-01-26 13:47

I am trying to automate the process of installing nuget packages into new visual studio projects. My idea is to reduce the time it takes to source all the packages via the nuget

相关标签:
2条回答
  • 2021-01-26 14:21

    note that you cannot simply drop a pre-built packages.config file into a new project and expect it to work. When installing, NuGet modifies the project file (.csproj) to include references and uses packages.config for downloading missing files (and update/conflict logic).

    Using VS 2017 (released stable versions 15.2 and higher) and the PackageReference style of referencing projects, you can simply drop a Directory.Build.props file into the root of your solution containing all the projects you need:

    <Project>
      <ItemGroup>
        <PackageReference Include="Autofac" Version="3.5.2 />
        <PackageReference Include="Topshelf" Version="3.2.0 />
      </ItemGroup>
    </Project>
    

    This will add these NuGet packages to all new projects in the solution without the need for the .csproj files to be modified. (note that after adding/editing this file, you need to close and re-open the solution. this should be fixed in the upcoming VS 2017 15.3 update for editing the file).

    0 讨论(0)
  • 2021-01-26 14:42

    Nuget already supports automation of installation and we can use nuget commandline to achieve this

    Everytime you add a nuget package in Visual Studio,it gets add to a file called packages.config file.

    E.g. will look like this

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="Autofac" version="3.5.2" targetFramework="net451" />  
      <package id="Microsoft.Owin" version="3.1.0" targetFramework="net452" />
      <package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net451" />
      <package id="Microsoft.Owin.Hosting" version="3.1.0" targetFramework="net452" />
      <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net451" />
      <package id="Owin" version="1.0" targetFramework="net451" /> 
      <package id="Topshelf" version="3.2.0" targetFramework="net451" />
    </packages>
    

    Every project you have in your solution will have packages.config file. You can go to the parent folder of all the projects and simply run comand 'nuget restore', it will get all the packages for you.

    For this to work, nuget.exe needs to be downloaded separately .More details on the nuget command line can be found here and here's the commandline reference

    Edit:

    Thanks @Martin Ullrich pointing out.Just to be clear, The above method will not add the references to project file automatically,it will only get the packages to the packages folder.In VS2017,the support is there which @Martin's answer addresses.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题