我有一个类库,它保存着我的通用存储库类IRepository<T>。每当我需要asp.net核心web项目中的存储库时,我只需用给定的类型实例化IRepository,并且可以正常使用它。然而,要做到这一点,我需要在我的StartUp.cs中这样做
services.AddScoped<IRepository<SomeType>>(x => new DocumentDbRepository<SomeType>(new DatabaseSettings(
Configuration.GetSection("DocumentDb").GetSection("DatabaseName").Value,
Configuration.GetSection("DocumentDb").GetSection("CollectionName").Value,
Configuration.GetSection("DocumentDb").GetSection("EndpointUri").Value,
Configuration.GetSection("DocumentDb").GetSection("Key").Value)));我不想对每一种类型的T都这样做,是否有一种通用的方法来执行上面的操作?
我试着做以下几件事:
services.AddScoped(typeof (IRepository<>), typeof(DocumentDbRepository<>));这就是我想要的,但是我需要用它需要的数据库设置实例化DocumentDbRepository。
现在我正在从appsettings.json中提取值,将值放入类DatabaseSettings中,然后将其交给DocumentDbRepository的构造函数。
我的问题是双重的:
1)能否实例化所提供的开放泛型类型的实现部分?即DocumentDbRepository
2)是否有更好的方法将db设置传递给我的存储库?我试图将IConfiguration对象传递给类库的构造函数,但是我似乎无法解析类库中的IConfiguration引用,因为IConfiguration似乎是asp net框架的一部分?
我在.NET框架之上使用asp网络核心(不是.NET核心).
编辑:
每个类型的区段字段都是相同的,即所有存储库都需要用相同的设置进行实例化。这设计不好吗?
发布于 2017-10-05 08:55:10
每种类型的区段字段都不同吗?如果不是,为什么不直接为您创建一个通用方法来调用所有这些内容呢?
public void doIt<T>()
{
services.AddScoped<IRepository<T>>(x => new DocumentDbRepository<T>(
new DatabaseSettings(Configuration.GetSection("DocumentDb").GetSection("DatabaseName").Value,
Configuration.GetSection("DocumentDb").GetSection("CollectionName").Value,
Configuration.GetSection("DocumentDb").GetSection("EndpointUri").Value,
Configuration.GetSection("DocumentDb").GetSection("Key").Value)));
}如果它们不同,则可以将字符串作为参数传递给泛型方法。
https://stackoverflow.com/questions/46581391
复制相似问题