8

ASP.NET Core 5: Make your options immutable

 3 years ago
source link: https://anthonygiretti.com/2020/08/19/asp-net-core-5-make-your-options-immutable/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ASP.NET Core 5: Make your options immutable

2020-08-19 by anthonygiretti

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:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <LangVersion>preview</LangVersion> </PropertyGroup> </Project>

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:

namespace DemoAspNet5.Models { public class SmtpConfiguration { public string Domain { get; init; } public int Port { get; init; } } }

Once done, you’ll need to register your options:

using DemoAspNet5.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting;

namespace DemoAspNet5 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services) { services.AddControllers();

var smtpConfiguration = new SmtpConfiguration(); Configuration.Bind("SmtpConfiguration", smtpConfiguration);

services.AddSingleton(smtpConfiguration); }

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

app.UseRouting();

app.UseEndpoints(endpoints => { endpoints.MapControllers();

endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); } } }

And now you are ready to consume them, and you won’t be able to modify your options, example:

using DemoAspNet5.Models; using Microsoft.AspNetCore.Mvc;

namespace DemoAspNet5.Controllers { [Route("api/[controller]")] [ApiController] public class ConfigController : ControllerBase { private readonly SmtpConfiguration _smtpConfiguration;

public ConfigController(SmtpConfiguration smtpConfiguration) { _smtpConfiguration = smtpConfiguration; }

[HttpGet("smtp")] public IActionResult GetSmtpConfig() { // _smtpConfiguration.Port = 570; Error CS8852 Init-only property or indexer 'SmtpConfiguration.Port' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

return Ok(_smtpConfiguration); } } }

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 ? 😉

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK