问题
I need to make a database call when the application starts up to set up some cache. I have custom DbContext class which has a HttpContext within to hold the current sql connection as follows:
public sealed class DataContext : IDataContext
{
IDbConnection connection = null;
IDbTransaction transaction = null;
Guid id = Guid.Empty;
List<String> ConnectionList;
public DataContext(string Con = RuntimeDTO.DEFAULTDB)
{
HttpContext context = AppHttpContext.Current;
if (context.Items[Con] == null)
{
connection = new SqlConnection(RuntimeDTO.DATABASE[Con]);
connection.Open();
id = Guid.NewGuid();
transaction = connection.BeginTransaction();
context.Items[Con] = this;
}
}
public IDbConnection GetConnection(string Con)
{
//Get connection
}
// some other code
}
Now I have the below in Business Layer
public class CoreAccessBO : ICoreAccessBO
{
IRightDAO _rightDAO;
public CoreAccessBO(IRightDAO rightDAO)
{
_rightDAO = rightDAO;
}
public void RetrieveAccess(RequestDTO coreDTO)
{
try
{
// make a DAL call here and set up cache here
var result = _rightDAO.GetAccessInfo().Result;
// set cache here.
}
catch (Exception ex)
{
throw ex;
}
}
}
& my data access class looks some thing like this.
public class RightDAO : IRightDAO
{
IDataContext _dataContext;
public RightDAO(IDataContext dataContext)
{
_dataContext = dataContext;
}
public async Task<AccessDTO> GetAccessInfo(RequestDTO requestDTO)
{
// make a d/b call here
}
}
What would be the best way of calling RetrieveAccess() in CoreAccessBO from startup.cs since, I also have HttpContext being used in DataContext for some purpose. I came across DefaultHttpContext class but does know how to figure out this. I also referred the link couldn't figure out how to do this. Do creating Middleware for this will be fine if yes then how to set HttpContext and avoid exceptions. Any suggestions are welcome.
来源:https://stackoverflow.com/questions/62169032/how-to-call-a-repository-on-application-startup-using-di-while-creating-httpcont