ASP.NET Core 5: Make your options immutable
Introduction
If you’ve been using ASP.NET Core 5 for a while, you’ll be delighted to learn that a major improvement of C# 9, in other words C# 9 (delivered with .NET 5) that allows the creation of immutable objects through Init-only properties. As a result, you’ll have the ability to set up your application options so that they’re immutable. After all, these are a kind of constants that you don’t necessarily want to change after initialization, or even ban it. So it’s possible with ASP.NET Core 5 and C# 9.
If you don’t know what are Init-only properties, you can read my article here: https://anthonygiretti.com/2020/06/16/introducing-c-9-init-only-properties/
Prerequisites
For now, .NET 5 and ASP.NET Core 5 are still in preview, if you want to be able to reuse the code I will show you you’ll need to install:
- Visual Studio 2019 preview
- .NET 5 preview (7 for now)
- Setup your csproj properly:
Configure options as immutable
I have already written an article you can read for more details here if you want to configure your options in a simpler way: https://anthonygiretti.com/2019/09/15/simplified-options-usage-in-asp-net-core-2/
I will take the same sample to show you how to make your options immutable, you just need to replace in your options class set by init:
Once done, you’ll need to register your options:
And now you are ready to consume them, and you won’t be able to modify your options, example:
As you can see you are not able to modifie your options, you’ll get a compiler exception: Error CS8852 Init-only property or indexer ‘{your property}’ can only be assigned in an object initializer, or on ‘this’ or ‘base’ in an instance constructor or an ‘init’ accessor.
Very practical feature isn’t it ? 😉