C# 如何在.net core中注册继承的通用存储库
我有一个从C# 如何在.net core中注册继承的通用存储库,c#,asp.net-core,dependency-injection,repository-pattern,asp.net-core-3.1,C#,Asp.net Core,Dependency Injection,Repository Pattern,Asp.net Core 3.1,我有一个从IDapperDbContext继承的通用存储库。如何在Startup.cs中注册通用存储库 代码如下: DapperDbContext: public abstract class DapperDbContext : IDapperDbContext { protected readonly IDbConnection InnerConnection; private DatabaseSettings dbSettings; protected Dapper
IDapperDbContext
继承的通用存储库。如何在Startup.cs
中注册通用存储库
代码如下:
DapperDbContext:
public abstract class DapperDbContext : IDapperDbContext
{
protected readonly IDbConnection InnerConnection;
private DatabaseSettings dbSettings;
protected DapperDbContext()
{
var dbOptions = Options.Create(new DatabaseSettings());
InnerConnection = new SqlConnection(dbOptions.Value.ConnectionString);
}
}
通用存储库接口
public interface IRepository<T>
{
Task<int> InsertAsync(T model);
}
您可以这样注册它们:
//Generic interface and implementation.
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));
services.AddScoped<IStudentRepository, StudentRepository>();
//通用接口和实现。
addScope(typeof(IRepository)、typeof(Repository));
services.addScope();
您可以这样注册它们:
//Generic interface and implementation.
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));
services.AddScoped<IStudentRepository, StudentRepository>();
//通用接口和实现。
addScope(typeof(IRepository)、typeof(Repository));
services.addScope();
我以前试过,但没有成功。获取异常无法在CreateHostBuilder
方法中的program.cs
文件中为服务类型“eSchool.api.Domain.Interfaces.IRepository1[T]”实例化实现类型“eSchool.api.Domain.Repository.Repository
1[T]”。仅供参考,我需要使用tableName作为参数@bolkay初始化Repository.cs
,可能是abstract
标志。是。那部分起作用了。但第二部分是如何完成的。例如,将表名作为参数注册StudentRepository@bolkayI以前试过,但没有成功。获取异常无法在CreateHostBuilder
方法中的program.cs
文件中为服务类型“eSchool.api.Domain.Interfaces.IRepository1[T]”实例化实现类型“eSchool.api.Domain.Repository.Repository
1[T]”。仅供参考,我需要使用tableName作为参数@bolkay初始化Repository.cs
,可能是abstract
标志。是。那部分起作用了。但第二部分是如何完成的。例如,将表名作为参数注册StudentRepository@博尔凯
public class StudentController : ControllerBase
{
private StudentRepository _studentRepository;
public StudentController(StudentRepository repository)
{
_studentRepository = repository;
}
[HttpPost]
public async Task<IActionResult> CreateStudent(Student student)
{
await _studentRepository.InsertAsync(student);
return Ok();
}
}
//Generic interface and implementation.
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));
services.AddScoped<IStudentRepository, StudentRepository>();