Multiple binaries from a single DotNet Core project configuration file

Viewed 862

I have code for a bunch of CLI utilities made to test/showcase a network library. The library is compiled into an assembly - DotNet Core DLL.

I have several CLI examples showing how to use the library, for example, one search is using paging functionality and another returns everything etc. Basically, each is a short standalone CLI program.

I have CS source files and csproj file targeting dotnet core. Below is the configuration:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="mylib>
      <HintPath>../../bin/Debug/netstandard2.0/publish/mylib.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>

I want to have one executable for each source file e.g. PGSample.cs will get compiled into PGSample.exe etc. How would I about achieving this?

1 Answers

I'm afraid you can have only one output per csproj, but there are some tricks to manage multiple projects easier.

You can put common build settings into a file named Directory.build.props in the root project folder, e.g.:

<Project>
    <PropertyGroup>
        <Authors>Your name here</Authors>
        <Company>Your company</Company>
        <Product>The project name</Product>
        <Version>1.6.18</Version>
        <PackageLicenseExpression>GPL-3.0-or-later</PackageLicenseExpression>
        <!-- e.g. bin/Release_net48/foo_cli/ -->
        <OutputPath>$(SolutionDir)bin\$(Configuration)_$(TargetFramework)\$(MSBuildProjectName)</OutputPath>
        <TargetFrameworks>net48</TargetFrameworks>
    </PropertyGroup>
</Project>

Then, add one subdirectory and minimal csproj file per output, e.g.

libfoo/libfoo.csproj: <Project Sdk="Microsoft.NET.Sdk" /> (really, that's it!)

foo_cli/foo_cli.csproj:

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup><OutputType>Exe</OutputType></PropertyGroup>
    <ItemGroup><ProjectReference Include="..\libfoo\libfoo.csproj" /></ItemGroup>
</Project>

Iff you have only one library and a lot of executables, you might even add your executable settings to the Directory.build.props:

[..]
<PropertyGroup Condition=" $(MSBuildProjectName) != 'libfoo'">
  <OutputType>exe</OutputType>
</PropertyGroup>
<ItemGroup Condition=" $(MSBuildProjectName) != 'libfoo'">
  <ProjectReference Include="..\libfoo\libfoo.csproj" />
</ItemGroup>
Related