razor icon indicating copy to clipboard operation
razor copied to clipboard

Update `@inject` to support keyed services

Open javiercn opened this issue 2 years ago • 7 comments

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.

javiercn avatar Sep 14 '23 09:09 javiercn

/cc @SteveSanderson @MackinnonBuck

javiercn avatar Sep 14 '23 09:09 javiercn

@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";
}

ebekker avatar Oct 10 '23 23:10 ebekker

Hi there, will this feature make it into .NET 8?

burkenyo avatar Nov 03 '23 03:11 burkenyo

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".

david-at-solve avatar Jan 23 '24 13:01 david-at-solve

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)

KarlWindhager avatar Oct 30 '24 14:10 KarlWindhager

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

WhitWaldo avatar Mar 06 '25 19:03 WhitWaldo

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 :) )

JSparshottO2 avatar Dec 16 '25 17:12 JSparshottO2