How to call a Repository on application startup using DI while creating HttpContext

一曲冷凌霜 提交于 2020-06-29 05:16:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!