Skip to content

Instantly share code, notes, and snippets.

@Stroniax
Last active August 25, 2023 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stroniax/6570317e6bea3a9f4e904d6b4c1f87a8 to your computer and use it in GitHub Desktop.
Save Stroniax/6570317e6bea3a9f4e904d6b4c1f87a8 to your computer and use it in GitHub Desktop.
Docker Mounted DotNet Watch Run

This gist demonstrates a problem experienced when using dotnet run within a docker container. The command works fine outside of the container, but when running the container we run into a problem wherein NuGet references cannot be resolved outside of the container, so vscode or visual studio will report problems if you start the compose project.

To test this out, copy the files to your computer in a new directory. Open the directory with either editor (vscode or vs). Run the following comand and observe the errors in your editor that appear at the using PSValueWildcard; statement in Program.cs.

docker build . -t docker-dotnet-watch && docker run -v .:/src docker-dotnet-watch
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PSValueWildcard" Version="1.0.0-alpha1" />
</ItemGroup>
</Project>
FROM mcr.microsoft.com/dotnet/sdk:7.0
WORKDIR /src
CMD dotnet build
using System;
using System.Threading;
// this reference fails to be resolved after running the compose project (or container alone)
using PSValueWildcard;
public sealed class Program
{
public static void Main()
{
Console.WriteLine("Hello, World!");
}
}
@Stroniax
Copy link
Author

https://natemcmaster.com/blog/2018/05/12/dotnet-watch-2.1/#support-for-running-in-docker

The solution is to add the following Directory.Build.props file to the project or solution directory.

<Project>

  <PropertyGroup>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/obj/**/*</DefaultItemExcludes>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/bin/**/*</DefaultItemExcludes>
  </PropertyGroup>

  <PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' == 'true'">
    <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/container/</BaseIntermediateOutputPath>
    <BaseOutputPath>$(MSBuildProjectDirectory)/bin/container/</BaseOutputPath>
  </PropertyGroup>

  <PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' != 'true'">
    <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/local/</BaseIntermediateOutputPath>
    <BaseOutputPath>$(MSBuildProjectDirectory)/bin/local/</BaseOutputPath>
  </PropertyGroup>

</Project>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment