001
001

Reputation: 65205

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

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

Upvotes: 3

Views: 2569

Answers (2)

Keith Nicholas
Keith Nicholas

Reputation: 44316

Generally when you find something you want to use in two places it's a candidate to be spun into it's own class. Then both controllers can use the common class.

Upvotes: 0

vittore
vittore

Reputation: 17589

There are several aspects we want to touch:

  • if code you have is useful in all controllers, most of the time it is good practice to create BaseApiController that will inherit from ApiController and put things that are used across all controllers there. (You also inherit your controllers from that class of course)

  • if code is some kind of business logic and is not strictly speaking related to handling http request one way or another ( i.e. you have model Square and you want to calculate area and return it from controller method). Things like that you want to refactor to specific service which might or might not be model, dedicated service, static class or something completely different

Upvotes: 7

Related Questions