My scenario: My application is a Web Api 2 application that uses a layer of business logic and a repository to access data. The web application uses ASP.NET impersonation to enter the database as the user accessing the website (authenticated through PKI). I have several asynchronous controller methods. However, when I'm awaitin data access methods, the database call may end in another thread, which will then access the database under the identifier of my application pool, which cannot connect to the database.
Example Controller :
public class TestApiController : ApiController {
private IBusinessLogicObject _myBlObject;
public TestApiController(IBusinessLogicObject myBlObject){
_myBlObject = myBlObject;
}
public async Task<int> CountMyJobs(string name){
return await _myBlObject.CountMyJobsAsync(name);
}
}
Example business logic :
public class BusinessLogicObject : IBusinessLogicObject
{
private IGenericRepository<Job> _jobRepository;
public BusinessLogicObject(IGenericRepository<Job> _jobRepository)
{
_jobRepository = jobRepository;
}
public Task<int> CountMyJobsAsync(string name)
{
using (WindowsIdentity.GetCurrent().Impersonate())
{
return _jobRepository.Where(i => i.Name == name).CountAsync();
}
}
}
using ( ), .
, , await , (CountAsync()), .
:
ActionFilter - , ( ) using?