DEV Community

Burak Kepti
Burak Kepti

Posted on

Injecting your interface at runtime with generic types.

In some situations, you need to inject your interface with unknown types. Assume that you have a main T type as a DB which you need to mark as deleted (soft delete) and need to be sure you can do the same operation for child tables. And you have one generic delete Interface for entities.

How would you call them :

`// Get your service type generically
Type serviceType = entity.CultureEntity == typeof(IDeleteBusiness<>).MakeGenericType(entity.Type);

//Get the related service from your startup.cs injection
object service = this.serviceProvider.GetRequiredService(serviceType);

//Get The method from the injected class
object? result = service
.GetType()
.GetMethod("MethodName"), [typeof(List)])?.Invoke(service, [requests]);`

All you need is to Invoke it after

Top comments (0)