I am using Net Core 5 and had not yet had a need to use anything other than the built in Dependency Injection. I now have a need to be able to resolve a specific service based on the value selected from a dropdown list of services in a UI.
Out of all the DI containers out there I have decided to delve a bit further into Autofac and think that using either named services and a factory pattern or keyed services will be the way to go but I am running into a bit of difficulty, here is an example;
I have an Interface that look like this
public interface IChartDataService<TSource, TTarget>
And I have services that have to implement this interface like this
public class TreantService : IChartDataService<SourceDto, TargetDto>
I am struggling to work out how I am supposed to register these services in the Autofac container. For named services I have tried to register like this
containerBuilder.RegisterGeneric(typeof(MarkOneService)).As(typeof(IChartDataService<,>)).Named<MarkOneService>("markone");
containerBuilder.RegisterGeneric(typeof(MarkTwoService)).As(typeof(IChartDataService<,>)).Named<MarkTwoService>("marktwo");
and I try to resolve them like this
var service = scope.ResolveNamed("markone", typeof(IChartDataService<,>));
also tried it this way
var service = scope.ResolveNamed("markone", typeof(IChartDataService<SourceDto,TargetDto>));
I cant have registered them correctly as this errors with saying that the service is not registered.
My preferred method would be to use Keyed services, that way I can make use of 'IIndex' but again this is stumping me as to how to register or whether what I am trying to do is even possible.
I am trying to register keyed services like this
containerBuilder.RegisterGeneric(typeof(MarkOneService)).As(typeof(IChartDataService<,>)).Keyed("markone", typeof(IChartDataService<,>));
OR
containerBuilder.RegisterType<MarkOneService>().As<IChartDataService<,>>().Keyed<IChartDataService<,>>("markone");
I am clearly missing something as I cant seem to get the syntax right to be able register correctly. When I do get the registration working I then cant resolve the service because of the open interface.
Also, as I would prefer to use keyed service I dont know how I would be able to get the injected service dictionary. This obviously wont work as it doesn't match my Interface
IIndex<string, IChartDataService> serviceDic
and this is syntactically invalid according to VS
IIndex<string, typeof(IChartDataService<,>)> serviceDic
OR
IIndex<string, IChartDataService<,>> serviceDic
I have spent way too much time on this now and I am going round in circles so could do with some tother insight as to where I may be going wrong, anybody any suggestions? can you point me to any examples of what I am trying to acheive please?