dotnet watch run
is a command that can be very handy while developing .NET applications.
Its similar to Nodemon in Node.js in that it watches for file changes and restarts the app with the new changes on file saved.
dotnet watch
can be quite slow though, it builds and restarts the app on save.
This can be quite awkward when running a huge api.
Good news is that with the new .NET 6 feature, hot reload which is integrated into dotnet watch
, we can make changes and apply them instantaneously without re-building the application. (There are some limitations and I will talk about them later).
Let's start by looking at dotnet watch
for .NET 5 and .NET 6.
.NET 5 with dotnet watch
In the picture below we have:
- To the left: A basic web api which prints .NET version, the process Id, and the time for each request.
- To the right: A script that invokes the web api
- The api is started with
dotnet watch run
Lets edit this by capitalizing version.
As we can see in the picture above, we had to rebuild the api for this change. The process id also changed. It took about 12 seconds for the api to be available again. This time obviously varies depending on you application rebuild and startup process.
.NET 6 with dotnet watch
Lets do the same change for .NET 6, capitalize version.
As we can see it took less then a second. Also note the dotnet watch
output: Hot reload of changes succeeded
and we kept the same process id.
Thats great, now we can have dotnet watch
running constantly and save a lot of time having the api available during development. But there are some limitations.
.NET 6 dotnet watch limitation
When executing dotnet watch
we are prompted with the following information:
There are situations when hot reload aren't available and we have to rebuild and restart our application (the same as we did in .NET 5). The url which is prompted contains a list of unsupported edits.
If dotnet watch
detects that the edit is rude it will ask you the following:
Option A is perfect because then we can fallback to rebuild and restart the application when needed and takes benefits from hot-reload when possible. Though, it would be nice to have a non-interactive default flag for this situation.
Thats pretty much it. I hope you also get good use out of the new hot reload features in dotnet watch
.
Happy coding!