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

Joh*_*hew 2 c# dependency-injection repository-pattern asp.net-core asp.net-core-3.1

我有一个继承自 的通用存储库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);
    }
}
Run Code Online (Sandbox Code Playgroud)

通用存储库接口

public interface IRepository<T>
{
    Task<int> InsertAsync(T model);
}
Run Code Online (Sandbox Code Playgroud)

通用存储库实施

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的学生资料库

public class StudentRepository: BaseRepository<Student>,IStudentRepository
{
    public StudentRepository(string tableName):base(tableName)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

如何注册这些服务并将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();
    }
}
Run Code Online (Sandbox Code Playgroud)

bol*_*kay 6

你可以这样注册它们:

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

services.AddScoped<IStudentRepository, StudentRepository>();
Run Code Online (Sandbox Code Playgroud)

  • 可能是“抽象”标志。 (2认同)