-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
DI resolve parameter using same ServiceKey #99084
Comments
Tagging subscribers to this area: @dotnet/area-extensions-dependencyinjection Issue DetailsI have a few classes that are set up using keyed services in DI. Currently I have to do one of the following: // classes are nice and clean
class A() { }
class B(A a) { public A A { get; } = a; }
// but registration is less convenient
services.AddKeyedSingleton<A>("first");
services.AddKeyedSingleton<B>("first", (sp, key) => new B(sp.GetRequiredKeyedService<A>(key))); or // injecting IServiceProvider doesn't feel graet
class A() { }
class B([ServiceKey] string name, IServiceProvider sp) { public A A { get; } = sp.GetRequiredKeyedService<A>(name); }
// but registration is cleaner
services.AddKeyedSingleton<A>("first");
services.AddKeyedSingleton<B>("first"); I would like to be able to do something like this instead: // classes are still fairly clean
class A() { }
class B([FromKeyedServices(something)] A a) { public A A { get; } = a; }
// registration is still clean
services.AddKeyedSingleton<A>("first");
services.AddKeyedSingleton<B>("first"); Not sure exactly what that would look like, a different attribute or something maybe. Or maybe some sentinel value to use in FromKeyedServices. But the idea is being able to say "from keyed services, but using the value that ServiceKeyAttribute would return"
|
I would see this as very helpful and I've seen that Aspire has the same "problem". They went with the first workaround |
Indeed a very useful feature. I'd suggest adding a new attribute, something like |
@dferretti I've provided a PR #102160 to address this issue. But apparently it has to go through API review. Could you please update the issue with a proposed API change as per referenced PR and mark it as api-suggestion? Or alternatively I can make a new issue and reference yours. |
Just ran into needing this as well. Was able to provide a factory to workaround the need, but it gets messy with multiple levels or multiple dependencies. Would be nice to have it built in |
PTAL @benjaminpetit |
I have a few classes that are set up using keyed services in DI. Currently I have to do one of the following:
or
I would like to be able to do something like this instead:
Not sure exactly what that would look like, a different attribute or something maybe. Or maybe some sentinel value to use in FromKeyedServices. But the idea is being able to say "from keyed services, but using the value that ServiceKeyAttribute would return"
The text was updated successfully, but these errors were encountered: