Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get configuration.section on Blazor Server project created with NetCore 6?

On previous Blazor Server projects, that have the Startup.cs I am using this code to retrieve configuration:

Startup.cs
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration){Configuration = configuration;}
...
StripeConfiguration.ApiKey = Configuration.GetSection("Stripe")["ApiKey"];
StripeConfiguration.ClientId = Configuration.GetSection("Stripe")["ClientId"];
....
}

But it does not work on new projects created with NetCore 6, so I copied the code below from this solution here and although it works,there is this warning: ASP0000: Calling ‘BuildServiceProvider’ from application code results in an additional copy of singleton services being created….

Program.cs
{
....
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetRequiredService<IConfiguration>();
StripeConfiguration.ApiKey = configuration.GetSection("Stripe")["ApiKey"];
StripeConfiguration.ClientId = configuration.GetSection("Stripe")["ClientId"];
....
}


  [1]: https://www.syncfusion.com/forums/156203/using-the-spinner-while-loading-a-form

How can the code be corrected to eliminate this additional service ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In ASP.NET 6 it happens automagically – WebApplication.CreateBuilder(args); initiates DI. So, you can simply do in Program.cs

StripeConfiguration.ApiKey = builder.Configuration.GetSection("Stripe")["ApiKey"];
StripeConfiguration.ClientId = builder.Configuration.GetSection("Stripe")["ClientId"];

Of course, it is possible to tailor the initialization; but the assumption is that in 99 per cent situations it won’t be necessary!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading