2021年5月5日星期三

How to resolve list of Open Generic Types .Net Core [duplicate]

how does one resolve multiple registrations of implementations. I want to get a list of implementors:

Registration:

services.AddScoped(typeof(IClient<>), typeof(Client1));  services.AddScoped(typeof(IClient<>), typeof(Client2));  

I'm trying to do this:

public class ClientFactory : IClientFactory  {      private readonly IServiceProvider _serviceProvider;        public ClientFactory(          IServiceProvider serviceProvider)      {          _serviceProvider = serviceProvider;      }        public IClient<ListingBase> GetClient(string clientName)      {          var clients = _serviceProvider.GetServices<IClient<ListingBase>>(); // listing base is abstracct class            // match by name - filter by name          // do stuff here            return (IClient<ListingBase>)clients.FirstOrDefault();      }  }  

Getting:

Exception while executing function: Importer. System.Linq.Expressions: An expression of type 'Client1' cannot be used to initialize an array of type 'IClient`1[....Abstract.ListingBase]

It does work when I only register one instance and do .GetService<IClient<ListingBase>>()

However I want to get a List of all implementors.

https://stackoverflow.com/questions/67410698/how-to-resolve-list-of-open-generic-types-net-core May 06, 2021 at 09:20AM

没有评论:

发表评论