Closed inayelle closed 3 months ago
I could reproduce this bug. MVC is using ActivatorUtilities
which cause this bug. I think the issue should be transferred to the runtime repo.
@Kahbazi Thanks for confirming that this repros.
Tagging @benjaminpetit to confirm whether or not we should transfer this to the runtime repo for a fix.
Yes I think we should transfer it, and assign it to me.
Tagging subscribers to this area: @cston See info in area-owners.md if you want to be subscribed.
Author: | inayelle |
---|---|
Assignees: | - |
Labels: | `bug`, `area-System.Linq.Expressions` |
Milestone: | - |
Hi @benjaminpetit
I filed this issue originally in the dotnet/aspnet repo because it reproduces specifically with injecting keyed services into aspnet controllers. If we hide the keyed injection behind a proxy class, like in the snippet below, then the resolution works as expected and no exceptions occur. I hope this fact may help.
public sealed class DefaultWeatherProviderProxy
{
private readonly IWeatherProvider _weatherProvider;
public DefaultWeatherProviderProxy([FromKeyedServices(WeatherProvider.OpenWeatherMap)] IWeatherProvider weatherProvider)
{
_weatherProvider = weatherProvider;
}
public string GetWeatherForCity(string city)
{
return _weatherProvider.GetWeatherForCity(city);
}
}
[ApiController]
[Route("weather")]
public sealed class WeatherController : ControllerBase
{
private readonly DefaultWeatherProviderProxy _defaultWeatherProvider;
public WeatherController(DefaultWeatherProviderProxy defaultWeatherProvider)
{
_defaultWeatherProvider = defaultWeatherProvider;
}
// ...
}
Tagging subscribers to this area: @dotnet/area-extensions-dependencyinjection See info in area-owners.md if you want to be subscribed.
The core issue is that ActivatorUtilities.CreateFactory()
can't be used with keyed services if the key 's type is a value type, so the issue isn't just with enums.
Hi @steveharter , just found that I had raised pr for this :)
Is there an existing issue for this?
Describe the bug
Let's say we have the following services:
And their registration in the dependency container using enum keys:
Having this, we can resolve a weather provider by interface and key using method injection in a controller (which works fine):
However, if we wanted to inject a default weather provider via constructor, like:
We won't be able to query any of the actions of this controller due to a controller activation failure with an exception:
I believe it doesn't work because the key in this example is an enum, which is a value type. If we replace the enum key with a string key, it all works like a charm.
Expected Behavior
It should be possible to resolve keyed services using
FromKeyedServices
attribute via controller constructor.Steps To Reproduce
Link to an example project: https://github.com/inayelle/keyed-services-api-example
Exceptions (if any)
.NET Version
8.0.100
Anything else?