C
C#12mo ago
cow

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:
public class GenericReportFactory
{
public IGenericReport GetReport(IServiceProvider serviceProvider, string reportType)
{
switch (reportType)
{
case MonthlyReportType.ThingOne:
return serviceProvider.GetRequiredService<ThingOneReport>();
case MonthlyReportType.ThingTwo:
return serviceProvider.GetRequiredService<ThingTwoReport>();
default:
return null;
}
}
}
public class GenericReportFactory
{
public IGenericReport GetReport(IServiceProvider serviceProvider, string reportType)
{
switch (reportType)
{
case MonthlyReportType.ThingOne:
return serviceProvider.GetRequiredService<ThingOneReport>();
case MonthlyReportType.ThingTwo:
return serviceProvider.GetRequiredService<ThingTwoReport>();
default:
return null;
}
}
}
//DI setup has:
services.AddTransient<IGenericReport, ThingOneReport>();
services.AddTransient<IGenericReport, ThingTwoReport>();
services.AddTransient<IGenericReportFactory, GenericReportFactory>();
//DI setup has:
services.AddTransient<IGenericReport, ThingOneReport>();
services.AddTransient<IGenericReport, ThingTwoReport>();
services.AddTransient<IGenericReportFactory, GenericReportFactory>();
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 Thanks
3 Replies
Sossenbinder
Sossenbinder12mo ago
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>();
Sossenbinder
Sossenbinder12mo ago
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
cow
cowOP12mo ago
Thanks very much. That's got it working. Very clear answer 👍 . And thank you for the extra links
Want results from more Discord servers?
Add your server