2017-08-03 46 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

相關問題