dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.58k stars 25.29k forks source link

Provide updated JsonPatch sample for new hosting model #23647

Open natelaff opened 2 years ago

natelaff commented 2 years ago

Show example with new hosting model for https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-6.0#json-patch-addnewtonsoftjson-and-systemtextjson

The current implementation results in warning

Warning ASP0000 Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

This is relevant to code

static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
{
    var builder = new ServiceCollection()
        .AddLogging()
        .AddMvc()
        .AddNewtonsoftJson()
        .Services.BuildServiceProvider();

    return builder
        .GetRequiredService<IOptions<MvcOptions>>()
        .Value
        .InputFormatters
        .OfType<NewtonsoftJsonPatchInputFormatter>()
        .First();
}

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Rick-Anderson commented 2 years ago

@pranavkm @captainsafia your analyzers are working.

@natelaff we'll try to get a sample for you.

Rick-Anderson commented 2 years ago

@natelaff would you be able to submit a PR to fix this?

natelaff commented 2 years ago

@Rick-Anderson i don't know how to fix this 🤷‍♂️ its Microsoft's guidance that is triggering the warning. I don't know the proper method hence me opening this issue ;)