ASP.NET Core - How to reuse methods created in one controller in another controller?

Viewed 1938

One way is to create use class inheritance, but is there any other way I could reuse methods that I created in one controller in another controller?

EDIT: should I use a custom basecontroller like this?


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();
    }
}
2 Answers
Related