c# - 如何在 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>));
希望这可以帮助
推荐阅读
- laravel - 密码重置电子邮件给laravel用户表中的任何用户
- javascript - JavaScript 在浏览器选项卡关闭和浏览器关闭时执行一些操作
- php - 如何将字符串转换为包含 2 个单词和空格的数组
- search - 寻找完全匹配?
- java - Java,搜索给定模式的文件并获取目录名和完整文件名
- javascript - Javascript 正则表达式为 div 着色
- excel - 让用户从 Excel 中打开的工作簿中选择一张工作表
- android - 在 Android 按钮中嵌入 HTML 链接
- listview - 如何从 uwp 的列表视图中更改所选项目?
- azure-cosmosdb - 为什么不越过 RU 时 COSMOS 会节流