3

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

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

Some methods need to query the database, so from what you are saying I should be using a custom base controller, see my example is that right?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.