1

IHttpContextAccessor is used in a utility class inside a constructor, how do i create an instance of that class in the controller.

// Utility class

public class DBRepository
    {

        private readonly IHttpContextAccessor _contextAccessor;

        public DBRepository(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
}

I have done this and I'm stuck in my controller.

public class HomeController : Controller
{

       using (DBRepository DBRepo=new DBRepository())
       {

       }
}

How to a pass on a IHttpContextAccessor parameter to the utility class

Vishal A
  • 159
  • 1
  • 10
  • This looks like a pattern supporting Dependency Injection. I would expect that *somewhere* there is registration code, so you don't need to worry about it. You can probably just have a constructor for HomeController that accepts a parameter of type DBRepository and it will get injected for you when the pipeline creates your controller. – GPW Dec 01 '17 at 12:08
  • Assuming it's asp.net Core (as you've tagged it as such), this code is likely in your Startup.cs class. – GPW Dec 01 '17 at 12:10
  • Possible duplicate of [How to add IHttpContextAccessor in the Startup class in the DI in ASP.NET Core 1.0?](https://stackoverflow.com/questions/38184583/how-to-add-ihttpcontextaccessor-in-the-startup-class-in-the-di-in-asp-net-core-1) – mjwills Dec 01 '17 at 12:11

1 Answers1

1

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

Shyju
  • 214,206
  • 104
  • 411
  • 497