Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
.net core register generic interface and retrieve them using getservice

I have interface IOrder<T> and FurnitureOrder<T> implements it

I need to register multiple implementations like this

services.AddSingleton(IOrder<Chair>, FurnitureOrder<Chair>())
services.AddSingleton(IOrder<Table>, FurnitureOrder<Table>())

Now I have need to retrieve all IOrder services and the types(e.g chair, table) to do some background work on it. Can I get it using GetServices API? if not possible, Please suggest if design changes needed

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

One way to do it is to introduce some common non-generic interface IOrder and register all services as it (something similar framework does for hosted services registration and execution):

interface IOrder
{
}

interface IOrder<T> : IOrder
{    
}

services.TryAddEnumerable(ServiceDescriptor.Singleton<IOrder, FurnitureOrder<Chair>>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IOrder, FurnitureOrder<Table>>());

And then you will be able either inject them as IEnumerable<IOrder> into your dependent class or use IServiceProvider.GetServices<IOrder>() call to resolve them.

Also note that next registration also should work:

services.AddSingleton<IOrder, FurnitureOrder<Chair>>()
services.AddSingleton<IOrder, FurnitureOrder<Table>>()

If you need generic registrations also you can automate non-generic registration with something like this (after registering all generic ones):

var serviceDescriptors = services
    .Where(descriptor => descriptor.ServiceType.IsConstructedGenericType)
    .Where(descriptor =>
        descriptor.ServiceType.GetGenericTypeDefinition() == typeof(IOrder<>));
foreach (var sd in serviceDescriptors)
{
    services.TryAddEnumerable(ServiceDescriptor.Transient(typeof(IOrder), 
        p => p.GetService(sd.ServiceType))); // or add desciptor creating new based on existing one  
}
over 4 years ago · Santiago Trujillo Relatório

0

Presume You mean during excecution of ConfigureServices? You could do this:

    services.AddSingleton(typeof(IOrder<Chair>), f => new ChairOrder());

    var listOf = new List<ServiceDescriptor>();
    using var enumerator = services.GetEnumerator();
    while (enumerator.MoveNext())
                    {
                        var interfaceType = enumerator.Current.ServiceType;
                        if (!interfaceType.IsGenericType) continue;
                        if (interfaceType.Name.StartsWith("iorder", System.StringComparison.OrdinalIgnoreCase))
                            listOf.Add(enumerator.Current);                          
                    }
                    var sp = services.BuildServiceProvider();
                    foreach(var serviceDescriptor in listOf)
                    {
                        var interfaceIWant = serviceDescriptor.ServiceType;
                        var objectToUse = sp.GetRequiredService(serviceDescriptor.ServiceType);                            
                        //TODO:
                    }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda