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();
}
}
答案 0 :(得分:2)
@jonno发布的休息很好,但您需要修改MyController
中的构造函数:
public class MyController : BaseController
{
public MyController(ApplicationDbContext context, IIdentityService identityService)
:base(conext, identityService)
{
}
答案 1 :(得分:1)
您的基本控制器可以像删除其他公共呼叫一样,并将2个私有值转换为受保护。因为您正在从MyController扩展BaseController,所以您不需要重新启动值,只需调用它们即可。例如:
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
}
}
和你的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();
}
}