[英]How to register IFileProvider for the dependency injection in asp.net core 2.2?
[英]How to register this dependency in ASP.NET Core?
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) {}
}
如何在 ASP.NET Core 中注册此依赖项?
AddScoped、AddTransient 和 AddSingleton 方法接收一个 serviceType 和 implementationType ,它们都作为Type
传递,最后都插入IServiceCollection
这是实现
private static IServiceCollection Add(
IServiceCollection collection,
Type serviceType,
Type implementationType,
ServiceLifetime lifetime)
{
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationType, lifetime);
collection.Add(serviceDescriptor);
return collection;
}
因此,回答您的问题,您可以将泛型类型注册为服务,而不是作为实现,因为您无法创建泛型类型的实例。 但是根据您的实现,您不能在没有在实现类型上指定泛型参数的情况下注册泛型类型。 这应该失败
services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass));
出现以下错误:
开放通用服务类型“BaseClass`1[T]”需要注册开放通用实现类型。 (参数“描述符”)
请参阅下面的定义
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
{
}
现在这也应该可以完美地工作
services.AddScoped(typeof(BaseClass<>), typeof(DerivedClass2<>));
或者
services.AddScoped(typeof(BaseClass<Entity>), typeof(DerivedClass2<Entity>));
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.