2017-08-03 48 views
0

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

回答

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

休息是罚款张贴@jonno但你需要修改构造函数中MyController

public class MyController : BaseController 
{ 
    public MyController(ApplicationDbContext context, IIdentityService identityService) 
     :base(conext, identityService) 
    { 
    } 
+0

酷感谢@TheVillageIdiot(这样一个有趣的名字;)) – 001

相关问题