Instructor-led online courses in ASP.NET Core, ASP.NET MVC, and ASP.NET Design Patterns. Read more...
Instructor-led online courses in ASP.NET Core, ASP.NET MVC, and ASP.NET Design Patterns. Conducted by Bipin Joshi on weekends. More details are available here.

Detect code changes and restart application using .NET Core file watcher

When you run a ASP.NET Core application using dotnet run CLI command, the application is started for you and made available at a specific URL and port. During development stage it's very common to make changes to C# code such as models, controllers, and other classes. To see these modifications in action you need to stop the application and again execute the dotnet run CLI command. Wouldn't it be nice if there is some way to detect such code changes and re-start the application automatically? Luckily, there is a tool called file watcher that does the trick. Let's see how.

The dotnet file watcher tool detects changes to your source code and re-starts your application. You can also use this tool to automatically run the tests. For ASP.NET Core 2.0 the file watcher tool is available as a NuGet package. For ASP.NET Core 2.1 it's included in the .NET Core SDK itself.

In this article I am going to use ASP.NET Core 2.0. So, I will add the required NuGet package in my application. Before we do that let's quickly see the usage of the filewatcher tool.

To use the file watcher tool you will invoke the following command :

> dotnet watch run

As you can see you simply added "watch" command to "dotnet run".

Ok. Now let's see the working of the tool with an example application. Have a look at the following web application build using ASP.NET Core MVC :

The application primarily consists of a model class called Employee, a controller named HomeController, and a view named Index.cshtml.

The Employee model class is shown below :

public class Employee
  public int EmployeeID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Country { get; set; }

The Employee class contains four public properties - EmployeeID, FirstName, LastName, and Country.

The HomeController's Index() action instantiates an Employee object and passes it to the Index view as shown below :

public class HomeController : Controller
    public IActionResult Index()
        Employee emp = new Employee();
        emp.EmployeeID = 1;
        emp.FirstName = "Nancy";
        emp.LastName = "Davolio";
        emp.Country = "USA";
        return View(emp);

As you can see, the Index() action simply assigns some values to various properties of Employee and passes it to the View() method.

The Index view simply displays these property values as follows :

@model DotNetWatcherDemo.Models.Employee


<h2>Employee ID : @Model.EmployeeID </h2>

<h2>Full Name : @Model.FirstName @Model.LastName</h2>

<h2>Country : @Model.Country</h2> 

Once you create the application as per the above setup, run it using the following .NET CLI command :

> dotnet run

You will see the following message in the console window :

If you open a browser and navigate to the URL shown by the dotnet run command, you will get the output as shown earlier in this article.

Now, let the application be in the running stage and change the HomeController's Index() as shown below :

public IActionResult Index()
    Employee emp = new Employee();
    emp.EmployeeID = 1;
    emp.FirstName = "Nancy";
    emp.LastName = "Davolio";
    emp.Country = "UK";
    return View(emp);

The above code changes the Country property from USA to UK.

Refresh the browser window. You won't see the changed property value on the page.

This confirms that the changes made to the code after running the application will call for restarting the application.

Now stop the application by pressing Ctrl + C in the console window.

Install the following NuGet package in the project :

Microsoft.DotNet.Watcher.Tools (version 2.0.2)

Then open the project's .csproj file and add an entry as shown below :

    <PackageReference Include="Microsoft.AspNetCore.All" 
Version="2.0.0" />
Version="2.0.2" />

Next, run the application using the following .NET CLI command :

> dotnet watch run

This time we simply added the "watch" command to the dotnet run. Your console should resemble like this :


Open the browser again and navigate to the URL as before. You will get output as shown at the beginning of this discussion.

Now again make changes to the HomeController's Index() action and change the Country property to some different value. As you make the changes and save HomeController.cs file you will see some logs in the console window. See below :

If you observe the logs, you will find that the changes to HomeController.cs have been automatically detected and the application has been restarted. If you refresh the browser window you will see the modified Country value displayed on the page.

Using Visual Studio to run the application

In  the preceding example, we  ran the application from the console. What it you want to utilize the features of the file watcher from within Visual Studio?

You can do that with the help of launchSettings.json file. Let's see how.

If you create and run a project using Visual Studio IDE rather than the .NET CLI commands, your project structure will look something like this :

Notice that under the Properties node you have a JSON file - launchSettings.json. This file contains certain settings that decide how the application is started. Visual Studio looks at these settings when you press F5 or Ctrl + F5.

Now, open launchSettings.json file and modify its Profiles section as shown below :

"Run using dotnet-watch": {
  "commandName": "Executable",
  "executablePath": "C:\\Program Files\\dotnet\\dotnet.exe",
  "workingDirectory": "$(ProjectDir)",
  "commandLineArgs": "watch run"

Here, we are adding a new launch profile whose name is - Run using dotnet-watch. The commandName is set to Executable because we want to invoke dotnet command line tool. executablePath is set to the path of dotnet.exe. The working directory is project's folder and commandLineArgs is set to watch run.

Carefully add the above launch profile and save launchSettings.json file.

If all goes well, you will find that you get this new profile in the Visual Studio toolbar as shown below :

Make sure that you select the newly created launch profile.

Ok. Now run the application by pressing Ctrl + F5 (because we want to change the controller from the VS itself). You will also find a console window being opened that shows the logs of the dotnet-watch command. Open a browser and navigate to the web page as before.

You can now change the Index() action by opening HomeController in the Visual Studio IDE and observe the console window for the logs as before.

To know more about the .NET file watcher tool go here.

That's it for now ! Keep coding !!

Bipin Joshi is a software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches online training courses in ASP.NET Core, Angular, and Design Patterns to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 13 August 2018

Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio

Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.