Reputation: 65137
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: 1
Views: 5523
Reputation: 40497
Rest is fine as posted by @jonno but you need to modify the constructor in MyController
:
public class MyController : BaseController
{
public MyController(ApplicationDbContext context, IIdentityService identityService)
:base(conext, identityService)
{
}
Upvotes: 2
Reputation: 41
Your base controller can be as is just remove the additional public call and convert the 2 private values to protected. Because you are extending BaseController from MyController, you dont need to re-instatiate the values, just call them. eg:
BaseController
public class BaseController : Controller
{
protected readonly ApplicationDbContext _context;
protected readonly IIdentityService _identityService;
public BaseController(ApplicationDbContext context, IIdentityService identityService)
{
_context = context;
_identityService = identityService;
}
//reusable methods
public async Task<Account> GetAccount()
{
//code to do something, i.e query database
}
}
And your MyController
public class MyController : BaseController
{
public async Task<IActionResult> DoSomething()
{
var account = await GetAccount();
//do something and you can call both _context and _identityService directly in any method in MyController
Return Ok();
}
}
Upvotes: 1