Lesson Weekend

The dotnet Watcher


Let's modify our dotnet run command to save us some more time. .NET 5 provides a tool called a watcher. A watcher will monitor our files for us. Let's run the watcher now.

$ dotnet watch run

This command tells .NET to watch our application and then execute the run command any time a change is made to our code.

Here's the output in the terminal when we run our watch command:

watch : Started

With console apps, usually the watch : Started message will quickly be replaced by the console UI. If you make a small change to the code, .NET will automatically run our program again. Try it out!

If you have an error in your project, the output will look something like this:

watch : Started
C:\Users\Guest\Desktop\car-dealership\Program.cs(20,31)
: error CS0103: The name 'fals' does not exist in the current context [C:\Users\
Guest\Desktop\car-dealership\car-dealership.csproj]

The build failed. Fix the build errors and run again.
watch : Exited with error code 1
watch : Waiting for a file to change before restarting dotnet...
watch : Shutdown requested. Press Ctrl+C again to force exit.

If you have such an error, you can simply fix it, save the file(s), and .NET will reload your program. Looking at the above terminal output, the error message is "The name 'fals' does not exist in the current context" and the location of the error is line 20 of Program.cs.

We can also use the watcher to run other dotnet commands, like build.

$ dotnet watch build

Which outputs

watch : Started
Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 36.51 ms for /Users/Guest/Desktop/wildlife-park/WildlifePark.csproj.
  WildlifePark -> /Users/Guest/Desktop/wildlife-park/bin/Debug/net5.0/WildlifePark.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.93
watch : Exited
watch : Waiting for a file to change before restarting dotnet...

This is great, because we can make changes to our code, then refer to the terminal to see the build output. Let's leave dotnet watch build running and make a change to our code.

Terminology


Watcher: Monitors files so we don't need to constantly type $ dotnet run. Here's how we add a watcher:

$ dotnet watch run

We can also do this with the build command:

$ dotnet watch build

Lesson 4 of 5
Last updated more than 3 months ago.