Çarşamba, 22 Mart 2017 / Published in Uncategorized

Here, we are going to see some live actions of the brand new Visual Studio 2017. Please note that this is not the complete series of new functionalities of Visual Studio 2017. Here, I am going to share only few things to get you started with the new Visual Studio 2017. I hope you will like this. Now let’s begin.


Today, the wait is over. Visual Studio 2017 is here, so I thought of trying it out today itself. That’s how this article is made. If you never use Visual Studio, you can find some articles and code snippets related to it here.

Installing Visual Studio 2017

You can always install the brand new Visual Studio 2017 from here. While installing, you can always select the things you may need, for example, if you are a Xamarin developer, you can select Xamarin. Visual Studio 2017 has the option for it. This makes the installation pretty much fast. Once after you install, it is time to launch.


You can always set the development settings and the theme as per your wish. These features are already available in other lower versions too. Just thought of saying it.


Recent, Open, New Project Template

In the start screen, you can see some slight changes as listed below:

  • Recent

    This is where your recent projects will be shown, so that you can easily open it up.

  • Open

    This, helps you to open the projects you need in an easy manner. It not only helps to open a project from your local computer, but also from Visual Studio Team services. Things are pretty much easier now. Right?

  • New project

    Here, you can see the templates that you recently worked with, and you can always search the templates too.


Creating First Visual Studio Applciation

Now, let’s create an empty MVC application and a controller in it.

namespace WhyVisualStudio2017.Controllers
    public class HomeController : Controller
        // GET: Home
        public ActionResult Index()
            return View();

Now, if you look at the preceding image, you can see that there are dotted lines between the namespaces, classes, methods.


This will help you to understand how the namespaces, class, methods are related to. If you have worked in heavy projects where you can have 1000s of lines of codes in a single class, you may find this feature very useful.

Now let’s create a model class as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WhyVisualStudio2017.Models
    public class Calculator
        public static int CalculateMe(int v1, int v2)
            return v1 * v2;

Go back to your controller and type ‘cal’, you can see the new intellisense, where you can separate the lists by classes, snippets, interfaces, etc.



Now, if you have given your function name as in camelCase manner, Visual Studio 2017 will give a suggestion to rename it as follows:


As an additional feature, if you click on the preview changes, you can get to know where exactly your recent code changes may affect and what fix you can give.


Searching for a file is much easier in Visual Studio 2017, all you have to do is type CTRL + T, then you can see a box as shown below:


You can select any kind of files by typing the file name as shown below:


You can always use the filters given there in the box.

Another important feature available in Visual Studio 2017 is, Exception User Handled. If you get any error, the Visual Studio 2017 will tell you where exactly the error is. For example, we all know the preceding codeblock will give you a null reference exception.

List<string> lstString = new List<string>();
lstString = null;

Now, if you run your application, Visual Studio 2017 will give you the entire details of the error as follows:


In the exception box, it has been mentioned as:

For every developer, one of the headaches is finding where exactly the error occurs. Now Visual Studio 2017 makes that much easier. Way to go. That’s all for today. I will come with all the features of Visual Studio 2017 very soon. Happy coding!.


See also


Did I miss anything you may think is needed? Could you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.

Your Turn. What Do You Think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Cuma, 17 Mart 2017 / Published in Uncategorized

We are pleased to announce updates to our ASP.NET tools, ASP.NET Core tools, Container tools, and frameworks that are shipping as part of the Visual Studio 2017 release today.  We have made significant updates to the web development tools to make them easier for you to use and help make you more productive in your daily web development tasks.

ASP.NET Core Tooling

As part of this release, we are including an RTM version of the ASP.NET Core tools.  Visual Studio 2015 included preview tooling based on project.json that supported the 1.0 and 1.1 versions of the ASP.NET Core framework. Visual Studio 2017 and it’s .csproj tooling is the tooling for ASP.NET Core moving forward. Customers should plan to migrate their applications to the new .csproj tooling.

With Visual Studio 2017, we have delivered updates that complete the experience for ASP.NET Core developers.  ASP.NET Core is available in the Web and .NET Core sections of new projects:

File – New – Project


The new ASP.NET Core project template screen has some minor updates, and still makes available the choice of three web templates: Empty, API, and Web Application

New Project Template

You can now choose to use ASP.NET Core 1.0 or 1.1 using the combo-box at the top of the screen.  Additionally, you can choose to add Container support to your project with the checkbox at the bottom-left of the screen.  This option adds:

  • Docker files to your project for building Container images
  • a Docker Compose project to define how you instance your Containers
  • Multi-project/container debugging support for Containers.

Default Web Application Project Structure

We are now shipping templates with the following features:

  • Bower enabled by default, delivering the bootstrap, jQuery, and jQuery validation libraries and added to the wwwroot/lib folder by default.
  • We removed the package.json file for npm integration
  • We removed gulpfile.js file for JavaScript task processing.

Existing projects using npm, grunt, or gulp will continue to enjoy the features we added for those frameworks, including the npm package management experience and the Task Runner Explorer. npm, Gulp, and Grunt features can still be added and enabled on new projects.  We now ship with a bundleconfig.json that activates the simplified resource bundler.  More information about configuring the bundler can be found on the extension’s GitHub wiki.

.NET Core csproj Support

Starting with Visual Studio 2017 and the .NET Core SDK 1.0 release, we exclusively support the updated MSBuild file format.  If you have an older project that uses the project.json format, it will be converted to the new format the first time you open it with Visual Studio 2017.

In the csproj project file for your project you will notice a dramatic simplification of the project references.

In particular, the project file now has the following features activated by default:

  • An “Sdk” attribute on the Project root-element that is set to “Microsoft.NET.Sdk.Web”. This instructs the project system to manage this project with tooling to support an ASP.NET Core project that delivers a web endpoint with appropriate defaults.
  • A collection of “PackageReference” elements. These items are NuGet packages that should be installed and referenced by our project.  The packages.config file is no longer needed.
  • A collection of “DotNetCliToolReference” elements. These items enhance the dotnet command-line tool to give it features necessary to build and manage this project.  In the sample above, it enables the Entity Framework tools and the User Secret manager.

New DotNet New Templates

The dotnet command-line tool has new templates for the creation of new .NET Core projects.  When you run “dotnet new” now, you will see a selection of templates that you can choose from:

dotnet new templates

This now makes it very easy to understand the project templates that are available, and the languages that are supported for each.  Additionally, it is very easy to create your own templates or download other templates to use.  Instructions for building your own templates are on the project templates wiki.  An in-depth walk-through of the dotnet new experience can be found on the .NET Blog.

Debug Your Applications with Google Chrome

Visual Studio has supported client-side JavaScript debugging with Internet Explorer for a long time.  With Visual Studio 2017, you can now add the Google Chrome browser to the list of supported client-side debuggers.  If you use Google Chrome as your browser at Debug time, you will be able to hit breakpoints and step through the JavaScript and TypeScript code executing in the browser.  More details about this feature are in the client-side debugging announcement blog post.

Container Tooling Updates

Containers are now easier than ever to use with your projects in Visual Studio 2017.  For your ASP.NET Core projects, you can choose to add Docker container support at project creation time, and you can also add Docker support to your existing projects by right-clicking on the project in the Solution Explorer and choosing the Add – Docker Support menu option.

To make it easier to work with single and multiple projects, we moved the docker-compose configuration to a separate project in your solution explorer.

Docker Compose Project

If you want to debug your project inside of the container, set the docker-compose project as the startup project.  You can still set your project as the startup project and debug on your local machine without effecting any containers.

Since we are using a standard docker-compose file, you are free to add other containers into the mix that should be launched when you debug your solution.  Add your favorite database, load-balancer, or other service images into your docker-compose to allow you to work with those resources while you debug your ASP.NET application. Those additional containers may be written in other languages, but you can still instance them during your debugging session.

When compiling your code, you can now build your solution directly in a Docker container, representing how your build system can compile your code. Running the following code will volume mount your solution, execute “dotnet restore” and “dotnet publish” in the container, generating the compiled output to place in your optimized Docker images.

docker-compose -f docker-compose.ci.build.yml up

ASP.NET with Windows Container Support

We didn’t limit our support for Docker containers to only the ASP.NET Core projects, we’ve added support for ASP.NET (.NET Framework) applications as well.  You can use the same commands to add Windows container support to your favorite ASP.NET Web Forms, MVC, or Web API projects easily.  These applications will launch and run inside of a Windows container that is configured with IIS and the latest version of the .NET Framework.

Before you can run .NET Framework in Windows Containers locally, make sure that you have the latest version of Docker for Windows and that you have switched to Windows Containers using the Docker systray icon.

Publish Your Application

When it comes time to publish your application, you will find a greatly improved experience when you choose the Publish action on your project.

Publish Your Project

You can now choose to publish to the following locations:

  • Azure App Service, including Linux Container Deployments (if Docker is enabled for your ASP.NET Core project)
  • IIS, FTP
  • A folder
  • An Azure Virtual Machine

If you have your application configured with Docker support, the publish option will allow you to publish your application as a container to your own Azure Container Registry and deploy to Azure App Service Linux using containers.

Options for Publication to Azure App Service

Publishing to your own container registry makes it easier for you to re-use your container to deploy new versions or more instances easily.

Recommended Visual Studio Extensions

There are two extensions that we recommend adding to your Visual Studio 2017 installation to assist with ASP.NET Core application development:

  • The Project File Tools extension provides intellisense for NuGet packages when hand-editing a csproj file
  • The Razor Language Service provides intellisense, syntax highlighting, and tooltip support for ASP.NET Core Razor Tag Helpers in Visual Studio 2017

To learn more about ASP.NET Core and Razor Tag Helpers, see the Intoduction to Tag Helpers in ASP.NET Core on the doc.microsoft.com website. To create your own custom Tag Helpers, see Introduction to Authoring Tag Helpers in ASP.NET Core.

Additionally, the new Web Essentials 2017 extension pack includes both of these extensions and a number of other helpful tools for any web developer.


Visual Studio 2017 is here and has the tools you need to be an effective web developer with ASP.NET, ASP.NET Core, and Docker container support.  Visual Studio Community is available for free to hobbyists and small companies with limitations, download a copy and get started being a more productive web developer today.

Çarşamba, 08 Mart 2017 / Published in Uncategorized

Today, we are releasing .NET Core Tools 1.0. It’s an exciting day and an important milestone in the .NET Core journey. The tools are supported on Windows, macOS and Linux. You can use them at the command-line, with VS Code or as part of Visual Studio 2017. Please check out the improvements to ASP.NET Core as well.

You can download the new .NET Core tools at .NET Core Downloads, for development at the command-line or with VS Code.

The tools are also integrated into Visual Studio 2017, also releasing today. You need to select the .NET Core cross-platform development workload when you install Visual Studio.

You can read more about the Visual Studio 2017 release in Announcing Visual Studio 2017 General Availability… and more. Also check out Visual Studio 2017: Productivity, Performance, and Partners.

Visual Studio for Mac also includes support for .NET Core. Visual Studio for Mac Preview 4 is releasing today.

Visual Studio Code works great with .NET Core, too. The C# extension is a must-have for .NET Core development, and is typically suggested to you as soon as you open a C# or csproj file.

New versions of the .NET Languages are included in Visual Studio. You can now use C# 7, Visual Basic 15 and F# 4.1. C# 7 is already supported with .NET Core (just by using the latest Roslyn!). We expect F# support in the first half of 2017 and then VB support after that.

.NET Core 1.0.4 and .NET Core 1.1.1 were also released today, for Windows, macOS, Linux and Docker. Both releases include a set of reliability updates to improve the quality of .NET Core. You can download the .NET Core Runtime releases via our .NET Core Runtimes download page. If you are looking for the .NET Core SDK to get the latest tools, try the .NET Core SDK download page.

A Quick Tour of .NET Core

There are some great experiences and features that we’ve built over the last several months, a big step forward over the tools that were previously available for .NET Core.

You can take the tour of .NET Core by watching What’s new in .NET Core and Visual Studio 2017. It’s a great video, showing you a lot of the new .NET Core experience in just 8 minutes.

We are encouraging everyone doing .NET Core development to move to Visual Studio 2017, including migrating from project.json to csproj. We will not be supporting csproj and MSBuild for .NET Core in Visual Studio 2015.

Let’s take a look at some of the key improvements, starting with the command-line experience, moving to Docker and then into Visual Studio.

Command-line experience

You can very quickly create and run a .NET Core app on your favorite OS. Let’s see what the experience looks like on Windows, creating and launching a .NET Core 1.0 console app. You need the .NET Core SDK installed for this experience.

C:\>dotnet new console -o myapp
The template "Console Application" created successfully.

C:\>cd myapp

C:\myapp>dotnet restore
 Restoring packages for C:\myapp\myapp.csproj...

C:\myapp>dotnet run
Hello World!

Docker experience

You can see a similar command-line experience using Docker. In this example, I’m creating and launching an ASP.NET Core 1.1 MVC site using a .NET Core SDK Linux Docker image with Docker for Windows (I prefer “Stable channel”). You just need Docker for Windows installed, configured to Linux containers for this experience. You do not need .NET Core installed. You can do the same thing with .NET Core and Windows containers.

C:\Users\rich>docker run -p 8000:80 -e "ASPNETCORE_URLS=http://+:80" -it --rm microsoft/dotnet

root@9ea6f0be8ef7:/# dotnet new mvc -o mvc --framework netcoreapp1.1
The template "ASP.NET Core Web App" created successfully.

root@9ea6f0be8ef7:/# cd mvc

root@9ea6f0be8ef7:/mvc# dotnet restore
 Restoring packages for /mvc/mvc.csproj...

root@9ea6f0be8ef7:/mvc# dotnet run
Hosting environment: Production
Content root path: /mvc
Now listening on: http://+:80
Application started. Press Ctrl+C to shut down.

I then navigated the web browser to http://localhost:8000 and saw the following page load, instantly. I still find this configuration amazing, loading ASP.NET sites from a Linux container, on Windows. Try it; it works!


Visual Studio Templates

There are new templates that you can use in Visual Studio 2017, for .NET Core, ASP.NET Core and .NET Standard. You can see them located in the new project dialog, displayed in the following screenshot.


You should use the ASP.NET Core template if you want to build web sites or services, use the .NET Core template for tools or .NET Core experimentation and use the .NET Standard (Class Library) templates for libraries that you want to use with multiple apps of different application types (for example, .NET Core, .NET Framework and Xamarin). There are also platform-specific class library templates (for example, .NET Core (Class Library) and .NET Framework (Class Library)) that enable you want to take advantage of APIs available in those respective platforms and not in .NET Standard.

The ASP.NET Core “new project” experience includes a version picker, making it easy to select the version of ASP.NET Core that you want. The selection controls both the .NET Core target framework and ASP.NET Core package versions. See the experience in the following screenshot.

Editing csproj files in Visual Studio

With .NET Core projects, you can the csproj project file “live” while the project is loaded. This option is available by right-clicking on the project file and selecting Edit [project-name].csproj. You can add or remove package references and other aspects of the project file. It seems magic compared to the existing Visual Studio “Unload Project” experience. You can also try an experimental extension that offers csproj intellisense. See the new experience in the following screenshot.

.NET Standard Project-to-Project References

.NET Standard libraries are a new project type that you can use in nearly all .NET project types. They are the replacement for and a big step forward over Portable Class Libraries. You can now reference .NET Standard projects and NuGet packages from .NET Framework, Xamarin and Universal Windows Apps. The image below shows a .NET Framework console app with a project dependency on a .NET Standard project, which has dependencies on two popular NuGet packages.

Migrating project.json Projects to csproj

We’re now encouraging Visual Studio 2015 users to migrate to MSBuild and csproj from project.json. As I stated above, we will not be supporting any of the new .NET Core tools in Visual Studio 2015. We also won’t be updating the Visual Studio 2015 project.json-based tools.

There are two experiences for migrating project.json projects. You can migrate project.json files on the command-line, with the dotnet migrate command. The command will produce a .csproj project file that you can use with the latest .NET Core tools or open in Visual Studio 2017.

You can also open .xproj files in Visual Studio 2017. Visual Studio will migrate your .xproj files for you, producing a .csproj file that you can use going forward for use with both Visual Studio 2017 and with the latest .NET Core tools at the command-line.

The migration always preserves your project.json file (in a backup folder), so it is easy to go back to your pre-migration state if needed. That said, preserving your pre-migrated project state in source control is still a good idea.

Visual Studio for Mac (Preview 4)

Visual Studio for Mac is an IDE for mobile-first, cloud-first workloads with support for building iOS, Android, and Mac apps in C# and F# with Xamarin, as well as web and server apps with .NET Core and ASP.NET Core. You’ll find the same Roslyn-powered compiler, IntelliSense code completion, and refactoring experience you would expect from a Visual Studio IDE. And, since Visual Studio for Mac uses the same MSBuild solution and project format as Visual Studio, developers working on Mac and Windows can share projects across Mac and Windows transparently.


.NET Core documentation and ASP.NET Core documentation have been updated to document the .NET Core Tools 1.0 and Visual Studio 2017 experience.

We still have a lot of work to do to improve and expand the docs and will endeavor to do just that. Like the .NET Core product, the .NET Core docs are open source. Please don’t hesitate to file issues and help us improve the docs with a pull request.

What’s in the release

We released the following today:

  • .NET Core Tools 1.0.0 – only ships in Visual Studio 2017
  • .NET Core Tools 1.0.1 – available in the SDK and via Docker SDK images
  • .NET Core Runtime 1.0.4 – available as a Runtime install or Docker image and in the .NET Core SDK
  • .NET Core Runtime 1.1.1 – available as a Runtime install or Docker image and in the .NET Core SDK

We didn’t intend to release two versions of the SDK on the same day. That would be silly! Instead, there is a good story! The short version of the story is that we missed an internally-set date to update the .NET Core Tools 1.0.0 release (the one going into Visual Studio 2017) to add support for some Linux distros, so were forced to create the 1.0.1 in order to make Fedora 24 and OpenSUSE 42.1 developers happy.

We also updated both .NET Core 1.0 and 1.1, with patch releases. Both releases contain reliability fixes and no new features. You can always read the .NET Core release notes to learn about our releases.


The latest .NET Core runtime and tools are available in the following .NET Core SDK Docker images:

  • 1.0.4-sdk
  • 1.0.4-sdk-nanoserver
  • 1.1.1-sdk
  • 1.1.1-sdk-nanoserver

You can also use the latest .NET Core Runtime Docker images, which are recommended for production deployments since they are much smaller than the SDK images:

  • 1.0.4-runtime
  • 1.0.4-runtime-nanoserver
  • 1.1.1-runtime
  • 1.1.1-runtime-nanoserver

We adopted changes to the Docker tag scheme we use at microsoft/dotnet. The “-projectjson” and “-msbuild” differentiation is now gone. The tags are significantly simpler, as you can see from the tags above.

We have changed the tags multiple times over the last few months. These changes were required to properly represent the changing nature of the product. We believe that we will no longer need to make significant tag scheme changes going forward and that we are now at “steady state”. Thanks to all .NET Core Docker users for your patience!

As previously stated, we will no longer be producing any project.json-based Docker images.

.NET for UWP

The final release of .NET for UWP also shipped today within the Visual Studio 2017.

.NET Native is now included within the Microsoft.NETCore.UniversalWindowsPlatform NuGet package, starting with version 5.3.0. This means that you can select the version of .NET Native you want to use by selecting a specific version of the Microsoft.NETCore.UniversalWindowsPlatform package (starting with version 5.3.0). This capability is new with Visual Studio 2017. By using NuGet, we can ship .NET Native updates more easily and it’s easier for you to select the version you want to use, per project.

Here are the steps:

  1. Right click on the project and select Manage NuGet Packages…
  2. Select the Microsoft.NETCore.UniversalWindowsPlatform NuGet package.
  3. Change the version to 5.3.0.
  4. Click the Update button.

If you do not see version 5.3.0 listed, make sure that the Package Source is set to nuget.org.

You can revert back to .NET Native 1.4 at any time by rolling back the Microsoft.NETCore.UniversalWindowsPlatform NuGet package from 5.3.0 to any earlier version such as 5.2.2 or 5.1.0. This can be done by following the same steps outlined above with the desired version.

Visual Studio 2017 RC comes with .NET Native 1.4 by default. This is the same version that is included in Visual Studio 2015 Update 3, with the addition of a few fixes. .NET Native 1.6 is not supported in Visual Studio 2015.


Thanks to everyone that helped to get .NET Core Tools to 1.0. There are so many people to thank that helped the product get to today and we thank you for your patience as we iterated on our tools. We hope that you are happy with the product, specifically the 1.0 tools. Sincerely, thank you!

I looked back in our blog history and found the first mention of .NET Core and related tools on this blog. Enjoy that. Certainly, much of what I wrote there remains true. There are some DNX-isms that we’d still like to bring back, too.

.NET Core 1.x is just the start of this new platform. We’re very excited to see what you do with it. We’ll listen closely to your feedback and look forward to working closely with many of you on GitHub. Also, .NET Standard 2.0 and .NET Core 2.0 will be released later this year. We’ll start talking about those releases on the blog before long.

Again, thanks so much for using the product and for helping us build it.

Note: You can always find our released builds documented in release notes.

Çarşamba, 08 Mart 2017 / Published in Uncategorized

Previous posts:

Visual Studio 2017, .NET Core SDK 1.0, F# 4.1

Yesterday, we had a big product launch! Visual Studio 2017 is here, and with it come the releases of .NET Core SDK 1.0, and F# 4.1. Check out the posts for all the details:

Get the bits now:


In last week’s episode, Phillip Carter gave a tour of F#. This episode is two full hours of delicious F# aimed mainly at C# developers with no prior F# experience:

This week, we’ll have two shows. First, Scott Hunter will give a recap of yesterday’s announcements and what they mean for .NET. Second, we’ll have Matt Watson from Stackify to talk about Prefix, a lightweight dev tool for the Web that shows real-time logs, errors, queries, and more. We’ll stream live on Channel 9 at 9:30AM Pacific Time on Wednesday, then 10AM on Thursday. We’ll take questions on Gitter’s dotnet/home channel and on Twitter. Please use the #onnet tag. It’s OK to start sending us questions in advance if you can’t do it live during the shows.

Happy Birthday .NET!

We have another Happy Birthday .NET video for you this week. John Shewchuk is a Technical Fellow in charge of developer experience. He worked on Visual InterDev, drove the first release of Visual Studio, and was part of the architectural team for the very first and subsequent releases of .NET.

Tool of the week: FNA

FNA is a reimplementation of the Microsoft XNA libraries. The main contributor to the project, Ethan Lee, has ported two dozen XNA games already, including FEZ, Bastion, and Terraria.

Game of the week: Pyre

Pyre is a role-playing game in which you lead a band of exiles to freedom. To do this, you must fight through ancient competitions that are spread across a mystical purgatory. Each battle will bring you and your party closer to their freedom as they gain access to new abilities. Pyre will feature both a campaign and a two-player versus mode, letting you challenge a friend to one of fast-paced ritual showdowns.

Pyre is being created by Supergiant Games using C# and their own custom engine. It is under development but will be launching on Steam and PlayStation 4.

User group meeting of the week: Linux and microservice architecture in NC

Tonight Wednesday, March 8, at 5:30PM in Morrisville, NC, the TRINUG.NET group holds a meeting on .NET, Linux, and microservice architecture.





New F# Language Suggestions:

Check out F# Weekly for more great content from the F# community.






And this is it for this week!

Contribute to the week in .NET

As always, this weekly post couldn’t exist without community contributions, and I’d like to thank all those who sent links and tips. The F# section is provided by Phillip Carter, the gaming section by Stacey Haffner, and the Xamarin section by Dan Rigby, and the UWP section by Michael Crump.

You can participate too. Did you write a great blog post, or just read one? Do you want everyone to know about an amazing new contribution or a useful library? Did you make or play a great game built on .NET? We’d love to hear from you, and feature your contributions on future posts:

This week’s post (and future posts) also contains news I first read on The ASP.NET Community Standup, on Weekly Xamarin, on F# weekly, and on Chris Alcock’s The Morning Brew.

Çarşamba, 08 Mart 2017 / Published in Uncategorized

Back in June, when ASP.NET Core was still in RC2, I wrote a post about reloading strongly typed Options when the underlying configuration sources (e.g. a JSON) file changes. As I noted in that post, this functionality was removed prior to the release of ASP.NET Core 1.0.0, as the experience was a little confusing. With ASP.NET Core 1.1.0, it's back, and much simpler to use.

In this post, I'll show how you can use the new IOptionsSnapshot<> interface to simplify reloading strongly typed options. I'll provide a very brief summary of using strongly typed configuration in ASP.NET Core, and touch on the approach that used to be required with RC2 to show how much simpler it is now!

tl;dr; To have your options reload when the underlying file / IConfigurationRoot changes, just replace any usages of IOptions<> with IOptionsSnapshot<>

The ASP.NET Core configuration system

The configuration system in ASP.NET Core is rather different to the approach taken in ASP.NET 4.X. Previously, you would typically store your configuration in the AppSettings section of the XML web.config file, and you would load these settings using a static helper class. Any changes to web.config would cause the app pool to recycle, so changing settings on the fly this way wasn't really feasible.

In ASP.NET Core, configuration of app settings is a more dynamic affair. App settings are still essentially key-value pairs, but they can be obtained from a wide array of sources. You can still load settings from XML files, but also JSON files, from the command line, from environment variables, and many others. Writing your own custom configuration provider is also possible if you have another source you wish to use to configure your application.

Configuration is typically performed in the constructor of Startup, loading from multiple sources:

public Startup(IHostingEnvironment env)  
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    Configuration = builder.Build();

public IConfigurationRoot Configuration { get; }  

This constructor creates a configuration object, loading the configuration found in each of the file sources (two JSON files and Environment Variables in this case). Each source supplies a set of key-value pairs, and each subsequent source overwrites values found in earlier sources. The final IConfigurationRoot is essentially a dictionary of all the final key-value pairs from all of your configuration sources.

It is perfectly possible to use this IConfigurationRoot directly in your application, but the suggested approach is to use strongly typed settings instead. Rather than injecting the whole dictionary of settings whenever you need to access a single value, you take a dependency on a strongly typed POCO C# class. This can be bound to your configuration values and used directly.

For example, imagine I have the following values in appsettings.json:

  "MyValues": {
    "DefaultValue" : "first"

This could be bound to the following class:

public class MyValues  
    public string DefaultValue { get; set; }

The binding is setup when you are configuring your application for dependency injection in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)  

With this approach, you can inject an instance of IOptions<MyValues> into your controllers and access the settings values using the strongly typed object. For example, a simple web API controller that just displays the setting value:

public class ValuesController : Controller  
    private readonly MyValues _myValues;
    public ValuesController(IOptions<MyValues> values)
        _myValues = values.Value;

    // GET api/values
    public string Get()
        return _myValues.DefaultValue;

would give the following output when the url /api/Values is hit:

Reloading strongly typed options in ASP.NET Core RC2

Now that you know how to read settings in ASP.NET Core, we get to the interesting bit – reloading options. You may have noticed that there is a reloadOnChange parameter on the AddJsonFile method when building your configuration object in Startup. Based on this parameter it would seem like any changes to the underlying file should propagate into your project.

Unfortunately, as I explored in a previous post, you can't just expect that functionality to happen magically. While it is possible to achieve, it takes a bit of work.

The problem lies in the fact that although the IConfigurationRoot is automatically updated whenever the underlying appsettings.json file changes, the strongly typed configuration IOptions<> is not. Instead, the IOptions<> is created as a singleton when first requested and is never updated again.

To get around this, RC2 provided the IOptionsMonitor<> interface. In principle, this could be used almost identically to the IOptions<> interface, but it would be updated when the underlying IConfigurationRoot changed. So, for example, you should be able to modify your constructor to take an instance of IOptionsMonitor<MyValues> instead, and to use the CurrentValue property:

public class ValuesController : Controller  
    private readonly MyValues _myValues;
    public ValuesController(IOptionsMonitor<MyValues> values)
        _myValues = values.CurrentValue;

Unfortunately, as written, this does not have quite the desired effect – there is an additional step required. As well as injecting an instance of IOptionsMonitor you must also configure an event handler for when the underlying configuration changes. This doesn't have to actually do anything, it just has to be set. So for example, you could set the monitor to just create a log whenever the underlying file changes:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IOptionsMonitor<MyValues> monitor)  

        vals =>
                .LogDebug($"Config changed: {string.Join(", ", vals)}");


With this in place, changes to the underlying appsettings.json file will be reflected each time you request an instance of IOptionsMonitor<MyValues> from the dependency injection container.

The new way in ASP.NET Core 1.1.0

The approach required for RC2 felt a bit convoluted and was very easy to miss. Microsoft clearly thought the same, as they removed IOptionsMonitor<> from the public package when they went RTM with 1.0.0. Luckily, a new improved approach is back with version 1.1.0 of ASP.NET Core.

No additional setup is required to have your strongly typed options reload when the IConfigurationRoot changes. All you need to do is inject IOptionsSnapshot<> instead of IOptions<>:

public class ValuesController : Controller  
    private readonly MyValues _myValues;
    public ValuesController(IOptionsSnapshot<MyValues> values)
        _myValues = values.Value;

No additional faffing in the ConfigureMethod, no need to setup additional services to make use of IOptionsSnapshot – it is all setup and works out of the box once you configure your strongly typed class using

public void ConfigureServices(IServiceCollection services)  

Trying it out

To make sure it really did work as expected, I created a simple project using the values described in this post, and injected both an IOptions<MyValues> object and an IOptionsSnapshot<MyValues> object into a web API controller:

public class ValuesController : Controller  
    private readonly MyValues _myValues;
    private readonly MyValues _snapshot;
    public ValuesController(IOptions<MyValues> optionsValue, IOptionsSnapshot<MyValues> snapshotValue)
        _myValues = optionsValue.Value;
        _snapshot = snapshotValue.Value;

    // GET api/values
    public string Get()
        return $@"
IOptions<>:         {_myValues.DefaultValue}  
IOptionsSnapshot<>: {_snapshot.DefaultValue},  
Are same:           {_myValues == _snapshot}";  

When you hit /api/Values this simply writes out the values stored in the current IOptions and IOptionsSnapshot<> values as plaintext:

With the application still running, I edited the appsettings.json file:

  "MyValues": {
    "DefaultValue" : "The second value"

I then reloaded the web page (without restarting the app), and voila, the value contained in IOptionsSnapshot<> has updated while the IOptions value remains the same:

One point of note here – although the initial values are the same for both IOptions<> and IOptionsSnapshot<>, they are not actually the same object. If I had injected two IOptions<> objects, they would have been the same object, but that is not the case when one is an IOptionsSnapshot<>. (This makes sense if you think about it – you couldn't have them both be the same object and have one change while the other stayed the same).

If you don't like to use IOptions

Some people don't like polluting their controllers by using the IOptions<> interface everywhere they want to inject settings. There are a number of ways around this, such as those described by Khalid here and Filip from StrathWeb here. You can easily extend those techniques to use the IOptionsSnapshot<> approach, so that all of your strongly typed options classes are reloaded when an underlying file changes.

A simple solution is to just delegate the request for the MyValues object to the IOptionsSnapshot<MyValues>.Value value, by setting up a delegate in ConfigureServices:

public void ConfigureServices(IServiceCollection services)  
    services.AddScoped(cfg => cfg.GetService<IOptionsSnapshot<MyValues>>().Value);

With this approach, you can have reloading of the MyValues object in the ValuesController, without needing to explicitly specify the IOptionsSnapshot<> interface – just use MyValues directly:

public class ValuesController : Controller  
    private readonly MyValues _myValues;
    public ValuesController(MyValues values)
        _myValues = values;


Reloading strongly typed options in ASP.NET Core when the underlying configuration file changes is easy when you are using ASP.NET Core 1.1.0. Simply replace your usages of IOptions<> with IOptionsSnapshot<>.