如何在.net核心中注册继承的通用存储库

问题描述 投票:0回答:1

我有一个通用的存储库,它是从IDapperDbContext继承的。我如何在Startup.cs中注册通用存储库。下面是代码片段

1.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);
    }
}

2。通用存储库接口

public interface IRepository<T>
{
    Task<int> InsertAsync(T model);
}

3。通用存储库实现

public abstract class Repository<T> : DapperDbContext, IRepository<T>
{
    private readonly string _tableName;
    public BaseRepository(string tableName) : base()
    {
        _tableName = tableName;
    }

    public async Task<int> InsertAsync(T t)
    {
        var insertQuery = GenerateInsertQuery();
        using (var scope = BeginTransaction())
        {
            using (Connection)
            {
                return await Connection.ExecuteAsync(insertQuery, t);
            }
        }
    }
}

4。我的学生资料库

public class StudentRepository: BaseRepository<Student>,IStudentRepository
{
    public StudentRepository(string tableName):base(tableName)
    {

    }
}

我如何在Startup.cs中注册这些服务,并按如下所示将其注入到我的控制器中?

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();
    }
}
c# asp.net-core dependency-injection repository-pattern asp.net-core-3.1
1个回答
0
投票

您可以这样注册它们:

//Generic interface and implementation.
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));

services.AddScoped<IStudentRepository, StudentRepository>();
© www.soinside.com 2019 - 2024. All rights reserved.