Skip to content
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

InvalidCastException when using keyed services with factory #400

Open
jansssson opened this issue Aug 15, 2024 · 2 comments
Open

InvalidCastException when using keyed services with factory #400

jansssson opened this issue Aug 15, 2024 · 2 comments

Comments

@jansssson
Copy link

Hi,

Found a bug when using keyed services along with a factory and key which isn't a string.
As I don't use keyed services explicitly (neither adding nor getting), I don't know how big of a problem this is.
In my case they're added by Microsoft.Extensions.Http.Resilience, and I only found the problem running AssertConfigurationIsValid().

In essence, when registering a factory for keyed services, the factory should get the original key object, but currently gets a "ToString" of the key, here: https://github.com/JasperFx/lamar/blob/v13.0.4/src/Lamar/IoC/Instances/Instance.cs#L123

I haven't tested, but something like changing this:
return service.KeyedImplementationFactory(s, name);
to this:
return service.KeyedImplementationFactory(s, service.ServiceKey);
might solve the problem.

Half of a repro/test (unrealistic, but still):

var myKey = new SomeClass { Name = "This is my key" };
collection.AddKeyedSingleton(typeof(SomeClass), myKey, (provider, key) =>
{
    var k = (SomeClass) key;    //Throws, key has been "stringified"
    return k;
});

...

container.GetRequiredKeyedService<SomeClass>(myKey);

This is very minor right now (hence, no PR, sorry), just thought I'd report it...

@jeremydmiller
Copy link
Member

@jansssson Hey, just luckily managed to see this. This issue is now the exhibit A in this:

https://jeremydmiller.com/2024/06/19/retiring-lamar-and-the-ghost-of-ioc-containers-past/

"@#$%@#$ Microsoft" is my response to this. Lamar is not going to support their wacky non-string keyed services. I'd rather just quit than waste time on every random David Fowler brain fart.

@jansssson
Copy link
Author

I get your point-of-view, guess you can toss this issue if you want.
I'll short-term ignore/work-around the problem, and long-term probably try to revert back to dotnet built-in DI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants