Update `@inject` to support keyed services
We added support for keyed services on the runtime as part of https://github.com/dotnet/aspnetcore/pull/50561. We should consider what syntax we want to use when this is exposed through the @inject directive.
Some options are:
@inject Key Type PropertyName.@inject Type Key PropertyName.@inject Type(Key) PropertyName.
This would be for Blazor and Razor pages, since both added support for it.
/cc @SteveSanderson @MackinnonBuck
@inject Type("Key") PropertyName
@* or *@
@inject Type["Key"] PropertyName
But either way I think the key needs to be quoted to distinguish a literal string from a reference to a const, e.g.:
@inject Type(Global.ServiceKey) PropertyName
@* or *@
@inject Type[Global.ServiceKey] PropertyName
static class Global
{
public const string ServiceKey = "Key";
}
Hi there, will this feature make it into .NET 8?
Or maybe something like
@inject(Key = "MyKey") MyType MyName
which alignes more to the traditional
[Inject(Key = "MyKey")] private MyType MyName { get; set; }
?
Or as a general alternative it could be helpful to attach all kinds of attributes to the generated property, which could also be non-key-related ones. This could then look like this:
@inject [Key("MyKey"), OtherAttribute] MyType MyPropName
Of course you would have to rethink the name of the "key identifying attribute".
Hi, we stumbled over the same issue. Is this here still active?
We also tried to add inject a keyed service like this:
@inject [FromKeyedServices("Key"))] IMyService MyService
That resulted in an error, that the FromKeyedServicesAttribute requires a parameter (which of course is there)
I would also like to see this be added as the alternative isn't nearly as clear to work with. I'd be in favor of a syntax that lets me reuse the existing FromKeyedServices attribute to specify the key as @KarlWindhager used above as it remains consistent with the original syntax in other injection contexts:
@inject [FromKeyedServices("key")] IMyService MyService
We would also love to see this added in some capacity. (I'd be happy with any of the suggestions provided so far and so will not provide any others :) )