-2
public abstract class BaseClass<T> {
    private ISomeinterface _param;
    
    public BaseClass(ISomeinterface param) {
        _param = param;
    }
}

public class DerivedClass : BaseClass<Entity> {
    public DerivedClass(ISomeinterface param) : base(param) {}
}

How to register this dependency in ASP.NET Core?

  • Do you want o register, multiple subclasses of your BaseClass and use your BaseClass as the injection parameter? If that is the case here you have an approach https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core – Zinov Jul 27 '20 at 17:08
  • Does this answer your question? [How to register multiple implementations of the same interface in Asp.Net Core?](https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core) – Zinov Jul 27 '20 at 17:08
  • No, it doesn't belong to me. Also, the questions is different. – Onur Kayabaşı Jul 27 '20 at 18:21

1 Answers1

0

AddScoped, AddTransient and AddSingleton methods receive a serviceType and and implementationType which both are passed as Type, at the end both are inserted on IServiceCollection Here is the implementation

private static IServiceCollection Add(
      IServiceCollection collection,
      Type serviceType,
      Type implementationType,
      ServiceLifetime lifetime)
    {
      ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationType, lifetime);
      collection.Add(serviceDescriptor);
      return collection;
    }

So answering your question, you can register a generic type as service, not as an implementation because you can't create an instance of a generic type. But based on your implementation you can't register your generic type without specifying on the implementation type the generic parameter. This should fail

services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass));

with the following error:

Open generic service type 'BaseClass`1[T]' requires registering an open generic implementation type. (Parameter 'descriptors')

See the definitions below

public abstract class BaseClass<T>
{

    public BaseClass()
    {
    }
}

public class DerivedClass : BaseClass<Entity>
{
    public DerivedClass() : base() { }
}

public class DerivedClass2<T> : BaseClass<T> where T: Entity
{
   
}

public class Entity
{

}

Now this should work perfectly as well

services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass2<>));

or

services.AddScoped(typeof(BaseClass<Entity>), typeof(DerivedClass2<Entity>));

Hope this helps

Zinov
  • 3,817
  • 5
  • 36
  • 70
  • This registration is "InvalidOperationException: Unable to resolve service for type 'DerivedClass' while attempting to activate 'API.Controllers.SomeController'." contains error – Onur Kayabaşı Jul 27 '20 at 19:49