How to create/get a class instance progamatically? (Maybe it's called a Factory?)
Hi guys,
Based on string/switch, I want to get a class. I'm new to dependency injection and I'm struggling to find examples, probably because I'm searching for wrong keywords (maybe it's not called a factory?)
This is what I have so far:
Currently I'm getting the error
No service for type 'ThingOneReport' has been registered.
I set a breakpoint at services.AddTransient<IGenericReport, ThingOneReport>();
and I confirm it definitely hits that line, so it should be registered
Thanks3 Replies
You register your ThingOneReport as IGenericReport
That means you will also have to resolve it as an IGenericReport
If you want to resolve your service by the concrete implementation, it would have to look like
services.AddTransient<ThingOneReport>();
services.AddTransient<ThingTwoReport>();
https://weblogs.asp.net/ricardoperes/net-8-dependency-injection-changes-keyed-services
This might also be interesting to you if you want to register multiple implementations as one type, but on the other hand still retain the possibility to resolve explicit implementations
Thanks very much. That's got it working. Very clear answer 👍 . And thank you for the extra links