Live Coding In .Net Core Using Dotnet Watch

One of the most overlooked features of .net core is the new “dotnet watch” command. With it, it allows you to have a “live reload” of your ASP.net core site running without having to either run the “dotnet run” command, or worse do the “Stop the process in Visual Studio. Write your changes. Recompile and run again” routine. The latter can be very annoying when all you are trying to do is do a simple one line fix.

If you are used to watches in other languages/tooling (Especially task runners like Gulp), then you will know how much of a boost watches are to productivity.

The Basics

I highly recommend creating a simple ASP.net core project to run through this tutorial with. The tooling can be a little finicky with large projects so it’s easier to get up and running with something small, then take what you’ve learned onto something a little larger.

First you need to install the nuget package that actually runs the watcher tool. Run the following from your package manager console.

For this demo, I have a simple controller that has a get method that returns a string value.

Open a command prompt in your project directory. Run the command “dotnet watch run”. Note that if you previously have run the “dotnet run” command with other flags (e.g. “dotnet run -f net451” to specify the framework), this will still work using the watch command. You should see something similar to the following :

This means you are up and running. If I go to http://localhost:5000/api/home, I should see my controller return “Old Value”.

Now I head back to my controller and I change the Get action to instead return “New Value”. As soon as I hit save on this file I see the following in my console window :

The first line tells us that it immediately picked up on the fact that we changed something in HomeController.cs and so it starts recompiling immediately. When we browse to http://localhost:5000/api/home we see our “New Value” shown immediately and we didn’t have to do anything else in terms of recompiling.

Debugging With Dotnet Watch

And now the big caveat of this feature. There doesn’t seem to be a way to always have your Visual Studio debugger on the latest instance of the running code. The dotnet watch command itself spins up kestrel to host your code, but it’s hard to identify the PID of this particular process. I assume that you should be able to attach your debugger to this process once you find it, but as soon as you edit your code, a new process is created, rendering your debugger useless.

For the most part, errors will flash by on your console window when they happen so should be easy to spot. Then when you actually need the full debugger experience like breakpoints, you will be able to attach it. Just don’t expect it to be “always on”.

Leave a Reply

Your email address will not be published. Required fields are marked *