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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.