【问题标题】:ASP.NET REST API without Entity Framework but with DAO'sASP.NET REST API 没有实体框架但有 DAO 的
【发布时间】:2019-08-04 18:14:20
【问题描述】:

我是 .NET 的新手,我正在尝试创建一个没有实体框架或其他任何东西的 REST API。

我想编写自己的 DAO,但我不知道应该如何从 API 请求传入的 APIControllers (ControllerBase) 访问 DAO。

所以基本上,我的问题是,从 ControllerBase 类访问 DAO 的最佳或常用方法是什么。 (ControllerBase 类是 API 调用进来的类,即:get、getById、add、delete、update)

描绘我的问题:

       -----------------------------
 ------ControllerBase for Students 
|      -----------------------------
|
| How can I access my DAO methods (get, update, delete, add,...) from
| the ControllerBase class. I look for a common way.
|
|       ------------
 ---->   StudentDAO
        ------------

当然我可以在ControllerBase中实例化一个DAO对象,但我认为应该有更好的解决方案。我也可以创建静态方法,但我想知道是否有更好的解决方案。

希望你们能理解我的问题。 非常感谢。

【问题讨论】:

    标签: c# asp.net .net api dao


    【解决方案1】:

    您可以尝试创建一个将与DAO一起操作的接口和类,然后在Startup类的ConfigureServices方法的依赖注入中注册它。

    public void ConfigureServices(IServiceCollection services) {
            services.AddScoped<IStudentDao, StudentDao>()
        }
    

    然后在控制器中你需要创建IStudentDao类型的字段和构造函数。

    public class StudentController : ControllerBase {
        private readonly IStudentDao _dao;
    
    public StudentController(IStudentDao dao) {
            _dao = dao;
    }
    

    【讨论】:

      【解决方案2】:

      根据您是否使用 .NET Core,您应该能够创建具有正确签名的接口,然后定义具有实际实现的服务。

      将该接口“注入”到您的控制器中,您将能够在控制器中的任何位置使用该 DAO。不过,请记住在“Startup.cs”类中使用 DI 注册您的接口。

      依赖注入将阻止使用实例化类并使事物变为静态。

      interface IDAO
      {
       // method signatures and properties here for the DAO
      }
      
      
      class DAO : IDAO
      { 
        // specific code about the DAO. such as connection to DBs, methods, props, etc...
      } 
      
      class StudentController:ControllerBase
      {
          private readonly IDAO _dao
          public StudentController(IDAO dao)
          {
            _dao = dao;
          }
      }
      

      在 Startupfile 中注册时,请查看 Transient/Scoped/Singleton 生命周期,并从中选择您认为最合适的。

      【讨论】:

        猜你喜欢
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多