You can create an interface for your class and have the Dependency Injection framework inject it for you.
public interface IDbRepository
{
// Add methods signature here
public List<Post> GetPosts();
}
public class DBRepository : IDbRepository
{
private readonly IHttpContextAccessor _contextAccessor;
public DBRepository(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
//implement those methods
public List<Post> GetPosts()
{
// to do : return a list of Posts
}
}
Now map this interface to your concrete implementation in the ConfigureServices
method of Startup
class
services.AddTransient<IDbRepository , DBRepository>();
Now you can use constructor injection in your controller
public class HomeController : Controller
{
private readonly IDbRepository repository;
public HomeController (IDbRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var posts = this.repository.GetPosts();
//to do : Return something
}
}
Now sure, why you want to access HttpContext in a data access method/class. HttpContext is more of a web layer stuff. Instead of directly passing the HttpContext thing, you can perhaps pass only the needed value to the data access method. This way you can keep the data access layer not rely too much on Httpcontext , which is web stuff