【问题标题】:ASP.NET Core - How to reuse methods created in one controller in another controller?ASP.NET Core - 如何在另一个控制器中重用在一个控制器中创建的方法?
【发布时间】:2018-01-10 10:34:06
【问题描述】:

一种方法是创建使用类继承,但有没有其他方法可以重用我在一个控制器中创建的方法在另一个控制器中?

编辑:我应该使用这样的自定义基本控制器吗?


public class BaseController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly IIdentityService _identityService;

    public BaseController(ApplicationDbContext context, IIdentityService identityService)
    {
        _context = context;
        _identityService = identityService;
    } 

    public BaseController()
    {
    }

     //reusable methods
     public async Task<Account> GetAccount()
     {
        //code to do something, i.e query database
     }


}

public class MyController : BaseController
{
    private readonly ApplicationDbContext _context;
    private readonly IIdentityService _identityService;

    public MyController(ApplicationDbContext context, IIdentityService identityService)
    {
        _context = context;
        _identityService = identityService;
    } 

    public async Task<IActionResult> DoSomething()
    {

      var account = await GetAccount(); 

      //do something

      Return Ok();
    }
}

【问题讨论】:

标签: c# class inheritance asp.net-core


【解决方案1】:

通常,当您在两个地方找到想要使用的东西时,它就是一个候选者,可以被旋转到它自己的类中。然后两个控制器都可以使用公共类。

【讨论】:

    【解决方案2】:

    我们想接触几个方面:

      1234563 (当然,您也可以从该类继承您的控制器) 1234563诸如您想重构为特定的服务之类的东西,它可能是也可能不是模型、专用服务、静态类或完全不同的东西

    【讨论】:

    • 有些方法需要查询数据库,所以从你说的我应该使用自定义的基本控制器,看我的例子对吗?
    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多