.net 6 DI ApplicationServices not contains in WebApplication

Viewed 2583
app.UseRequestLocalization(app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);

I want to globalization in my project using .net 6. However in program.cs I get an error

Error CS1061
'WebApplication' does not contain a definition for 'ApplicationServices' and no accessible extension method 'ApplicationServices' accepting a first argument of type 'WebApplication' could be found (are you missing a using directive or an assembly reference?)

What can I do?

2 Answers

app should be casted into an interface as shown below:-

var options = ((IApplicationBuilder)app).ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();

app.UseRequestLocalization(options.Value);

In the .Net 6 ApplicationServices are accessible as the app.Services which returns IServiceProvider. You can try like this.

var options = app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
Related