Compile a ASP.NET Core Web App on the fly using dotnet watch command

One of the mostly used feature in Visual Studio while developing ASP.NET web applications is the ablity to make changes on the fly in the source code and able to see the changes in the browser without doing a compilation process manually. Actually Visual Studio tracks the changes made in the code and when you save the modifications, VS will automatically compile the changes in the background and restrats the session.

In the .NET Core world, most of the development is happening with code editors such as Notepad, Visual Studio Code etc. These are vanilla text editors and lacks most of the features found in Visual Studio. So .NET Core team has created a command line tool called dotnet watch to achieve this ability for .NET Core. It's basically a file watcher which restarts the specified application whenever there is change is made in the source code. You can read more about it in the documentation hosted in GitHub.

To add this functionlity in your code, you need to add the reference in the tools section in the project.json file as shown below.

"tools": {
    "Microsoft.DotNet.Watcher.Tools": "1.0.0-preview2-final"  
  }

After adding the entry in the tools, you needs to restore the package using the dotnet restore command to get all the required files for the watch tool.

Syntax

dotnet watch <dotnet arguments>

The watch tool can be used to compile, run application or test and publish whenever there is a change in the source code. So the <dotnet arugments> can be compile, run, publish etc. For the run command the usage is as shown below

Usage

dotnet watch run

Now, if you make any changes in server side code, the application will be automatically compiled and the reflected changes can be seen by just refreshing the browser.  In the following animation, if you look closely in the Terminal Window you can see that the application is stopped and compiled automatically when the source code is saved after making the changes.

So using this tool, whenever we need to make change in the source code there is no need to stop the running instance and executing the dotnet run command again. Similary it can be used along with any other dotnet command as discussed in the post here in the documentation.


No Comments

Add a Comment