MVC 6 如何在我的控制器中包含 BaseRepository class

MVC 6 How can I include a BaseRepository in my controller class

我正在使用 ORM 连接到名为 dapper 的数据库。它的问题是它的数据库调用是同步的,我最近按照这个简短的教程 http://www.joesauve.com/async-dapper-and-async-sql-connection-management/ 找到了一种使其异步的方法。我的问题是如何将这个 BaseRepository 带入我的 Controller class ?这是那个网站上的代码,和我的一样

BaseRepository- 顺便说一句,这段代码没有问题

 public abstract class BaseRepository 
   {

private readonly string _ConnectionString;

protected BaseRepository(string connectionString) 
{
    _ConnectionString = connectionString;
}

protected async Task<T> WithConnection<T>(Func<IDbConnection, Task<T>> getData) 
{
    try {
        using (var connection = new SqlConnection(_ConnectionString)) {
            await connection.OpenAsync(); // Asynchronously open a connection to the database
            return await getData(connection); // Asynchronously execute getData, which has been passed in as a Func<IDBConnection, Task<T>>
        }
    }
    catch (TimeoutException ex) {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL timeout", GetType().FullName), ex);
    }
    catch (SqlException ex) {
        throw new Exception(String.Format("{0}.WithConnection() experienced a SQL exception (not a timeout)", GetType().FullName), ex);
    }
}

}

现在他是这样带进来的

public class PersonRepository : BaseRepository
{
    public PersonRepository(string connectionString): base (connectionString) { }

    public async Task<Person> GetPersonById(Guid Id)
    {
        return await WithConnection(async c => {

            // Here's all the same data access code,
            // albeit now it's async, and nicely wrapped
            // in this handy WithConnection() call.
            var p = new DynamicParameters();
            p.Add("Id", Id, DbType.Guid);
            var people = await c.QueryAsync<Person>(
                sql: "sp_Person_GetById", 
                param: p, 
                commandType: CommandType.StoredProcedure);
            return people.FirstOrDefault();

        });
    }
}

我遇到问题的部分是 public class PersonRepository : BaseRepository 因为 Asp.Net 控制器以 public class HomeController: Controller ,我需要访问 WithConnection 方法才能使其正常工作。我的控制器看起来像这样

 public class HomeController : Controller
    {

        public class ConnectionRepository : BaseRepository
        {
            public ConnectionRepository(string connectionString) : base(connectionString) { }

        }
      public async Task<ActionResult> topfive()
            {
    // I get Error on WithConnection as it can't see the BaseRepository
                return await WithConnection(async c =>
                {


                    var topfive = await c.QueryAsync<Streams>("select * from streams ").ToList();
                return View(topfive);
                });

 }
            }

我显然不能用 BaseRepository 覆盖我的 ActionResult 方法,因为它会为所有类型的错误提供任何建议?

你必须插入 "Controller" 的 "BaseRepository"。我认为这对你有用。然后只需使用以下代码:

public abstract class BaseRepository : Controller 
{ 
// do you work
}


public class PersonRepository : BaseRepository
{
public PersonRepository(string connectionString): base (connectionString) { }

public async Task<Person> GetPersonById(Guid Id)
{
    return await WithConnection(async c => {

        // Here's all the same data access code,
        // albeit now it's async, and nicely wrapped
        // in this handy WithConnection() call.
        var p = new DynamicParameters();
        p.Add("Id", Id, DbType.Guid);
        var people = await c.QueryAsync<Person>(
            sql: "sp_Person_GetById", 
            param: p, 
            commandType: CommandType.StoredProcedure);
        return people.FirstOrDefault();

    });
   }
}

为什么要使用继承而不是组合?比如:

public class PersonRepository : BaseRepository
{
    public PersonRepository(string connectionString): base (connectionString) { }

    public async Task<Person> GetPersonById(Guid Id)
    {
        return await WithConnection(async c => {

            // Here's all the same data access code,
            // albeit now it's async, and nicely wrapped
            // in this handy WithConnection() call.
            var p = new DynamicParameters();
            p.Add("Id", Id, DbType.Guid);
            var people = await c.QueryAsync<Person>(
                sql: "sp_Person_GetById", 
                param: p, 
                commandType: CommandType.StoredProcedure);
            return people.FirstOrDefault();

        });
    }
    }

        public class ConnectionRepository : BaseRepository
        {
            public ConnectionRepository(string connectionString) : base(connectionString) { }

        }
      public async Task<List<TopFileClass>> topfive()
            {
    // I get Error on WithConnection as it can't see the BaseRepository
                return await WithConnection(async c =>
                {


                    var topfive = await c.QueryAsync<Streams>("select * from streams ").ToList();
                return topfive;
                });

 }

public class HomeController : Controller
{
   private readonly PersonRepository _repo;

   public HomeController(PersonRepository repo)
   {
       _repo = repo;
   }

   public async Task<ActionResult> TopFive() 
   {
       var top5 = await _repo.topfive();
       return View(top5);
   }
}

如果您不熟悉如何使存储库自动注入构造函数,请阅读 MVC 6 中的依赖注入。