Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
En C #, ¿cómo inyectar todas las instancias de la interfaz genérica en un solo constructor usando la clase base del genérico?

He definido la siguiente interfaz:

 public interface ICustomService<T> where T : CustomObject { IEnumerable<T> GetById(int Id); ... }

Y 2 implementaciones donde MyObject1 y MyObject2 heredan de CustomObject

 public class CustomService1 : ICustomService<MyObject1> { public IEnumerable<MyObject1> GetById(int Id) { ... } }
 public class CustomService2 : ICustomService<MyObject2> { public IEnumerable<MyObject2> GetById(int Id) { ... } }

Intento registrar ambos como ICustomService<CustomObject> pero aparece el error:

No hay una conversión de referencia implícita de 'CustomerService1' a 'ICustomService<CustomObject>'

En lugar de registrarse así:

 services.AddTransient<ICustomService<MyObject1>, CustomService1>(); services.AddTransient<ICustomService<MyObject2>, CustomService2>();

Al registrarme como arriba, mis services IEnumerable están vacíos:

 public ThirdService(IEnumerable<ICustomService<CustomObject>> services) { }

¿Cómo puedo inyectar toda la implementación de ICustomService en ThirdService ?

Estoy tratando de hacer esto para que ThirdService pueda recibir una identificación y luego obtener todos los CustomObject con esa identificación usando GetById en todos los servicios.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Suponiendo que no haya métodos de interfaz adicionales que tengan parámetros de tipo T , propiedades mutables de tipo T o métodos que devuelvan un tipo genérico que use T de forma no covariante, puede hacer que T sea covariante utilizando out

 public interface ICustomService<out T> where T : CustomObject

Esto haría que su intento de registro fuera válido:

 services.AddTransient<ICustomService<MyObject>, CustomService1>(); services.AddTransient<ICustomService<MyObject>, CustomService2>();

La covarianza garantiza que CustomService1 y CustomService2 se puedan usar de forma segura en lugar de ICustomService<MyObject> , a pesar de que ambos declaran una subclase de MyObject como argumento genérico.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!