8

Compile your changes on the fly with .NET Core Watch

You’ve set up your .NET Core web app, and maybe added MVC to it.

As you work on your site, you’ll find yourself repeating the following over and over again.

CTRL-C (to stop the application)

dotnet run

This gets a little frustrating after a while.

Watch for changes

The good news is you can use dotnet watch to solve the problem once and for all.

Add the following to your project.json.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "preserveCompilationContext": true,
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "tools": {
    "Microsoft.DotNet.Watcher.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": "portable-net451+win8"
    }
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
        "Microsoft.AspNetCore.Mvc": "1.0.0",
        "Microsoft.AspNetCore.Mvc.Core": "1.0.0"
      },
      "imports": "dnxcore50"
    }    
  }
}

.NET Core tools are scripts that can be added to your project and executed during the build process. Unlike dependencies, they are are not accessible to the code in the project.

For example, you might have tools to analyse/generate code, or (as in this case) automate an otherwise manual process.

dotnet-watch monitors your application’s files and restarts your app when you make changes to your source code.

Make sure your dev machine has dotnet-watch by restoring packages.

dotnet restore

Test it out

Now all you need to do is run the usual command but add watch to it.

dotnet watch run

You should see something like the following….

DotNet Watch

Now make some changes to your app. Every time you save your source code you’ll see your application is automatically recompiled.

In Summary

Laziness (er, I mean efficiency) triumphs again!

Update: 20th November 2016
In the original version of this article I used a wildcard to reference the latest version of dotnet watch 1.0.0 as follows.

  "tools": {
    "Microsoft.DotNet.Watcher.Tools": {
      "version": "1.0.0-*",
      "imports": "portable-net451+win8"
    }

The wildcard basically says you don’t care which flavor of 1.0.0 is used, just grab the latest one. This worked fine until a newer preview (preview 3) was released targeting a newer version of .NET Core (1.1). This now meant the app (using .Net Core 1.0.0) was out of sync with Preview 3 of .Net Watch which required .NET Core 1.1.

Scott Hanselman has posted a detailed write-up about this issue but the takeaway is to stick to specific versions if you want to guarantee that your app continues to work as you’d expect (and keep you in control of upgrading versions).