RDG013: Invalid source attributes
Value | |
---|---|
Rule ID | RDG013 |
Fix is breaking or non-breaking | Non-breaking |
Cause
This diagnostic is emitted by the Request Delegate Generator when an endpoint contains a route handler with a parameter that contains an invalid combination of service source attributes.
Rule description
ASP.NET Core supports resolving keyed and non-keyed services via dependency injection. It's not feasible to resolve a service as both keyed and non-keyed. The following code produces the diagnostic and throws a run time error with the same message:
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0,
AppJsonSerializerContext.Default);
});
builder.Services.AddKeyedSingleton<IService, FizzService>("fizz");
var app = builder.Build();
app.MapGet("/fizz", ([FromKeyedServices("fizz")][FromServices] IService service) =>
{
return Results.Ok(service.Echo());
});
app.Run();
How to fix violations
Resolve the target parameter as either a keyed or non-keyed service.
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0,
AppJsonSerializerContext.Default);
});
builder.Services.AddKeyedSingleton<IService, FizzService>("fizz");
builder.Services.AddKeyedSingleton<IService, BuzzService>("buzz");
builder.Services.AddSingleton<IService, FizzBuzzService>();
var app = builder.Build();
app.MapGet("/fizz", ([FromKeyedServices("fizz")] IService service) =>
{
return Results.Ok(service.Echo());
});
app.MapGet("/buzz", ([FromKeyedServices("buzz")] IService service) =>
{
return Results.Ok(service.Echo());
});
app.MapGet("/fizzbuzz", ([FromServices] IService service) =>
{
return Results.Ok(service.Echo());
});
app.Run();
public interface IService
{
string Echo();
}
public class FizzService : IService
{
public string Echo() => "Fizz";
}
public class BuzzService : IService
{
public string Echo() => "Buzz";
}
public class FizzBuzzService : IService
{
public string Echo()
{
return "FizzBuzz";
}
}
[JsonSerializable(typeof(string[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
When to suppress warnings
This warning should not be suppressed. Suppressing the warning leads to a NotSupportedException runtime exception The FromKeyedServicesAttribute is not supported on parameters that are also annotated with IFromServiceMetadata.
ASP.NET Core
Σχόλια
https://aka.ms/ContentUserFeedback.
Σύντομα διαθέσιμα: Καθ' όλη τη διάρκεια του 2024 θα καταργήσουμε σταδιακά τα ζητήματα GitHub ως μηχανισμό ανάδρασης για το περιεχόμενο και θα το αντικαταστήσουμε με ένα νέο σύστημα ανάδρασης. Για περισσότερες πληροφορίες, ανατρέξτε στο θέμα:Υποβολή και προβολή σχολίων για