0

I am looking forward to inject RequestContext, per request in .Net Core. inside the service collection.

Someone attempted 8 yrs. ago. ASP.NET MVC inject per request

public interface IMvcDepency
    {
        string PathValue { get; set; }
    }

public class FakeMvcDepency : IMvcDepency
{
    public string PathValue { get; set; }
}

public class MvcDepency : IMvcDepency
{
    public string PathValue { get; set; }

    public MvcDepency(HttpRequest req)
    {
        PathValue = req.Path.Value;
    }
}

And inject it somewhere in startup, as follows:

services.AddTransient<IMvcDepency, MvcDepency>(x => x.???);

or in OnActionExecuting like below:

public override void OnActionExecuting(ActionExecutingContext actCtx)
    {
        MvcDepency mvcDepency = actCtx.HttpContext.RequestServices.GetService(typeof(IMvcDepency)) as MvcDepency;
        mvcDepency = new MvcDepency(actCtx.HttpContext.Request);
        actCtx.HttpContext.RequestServices.AddService(mvcDepency);// AddService method doesn't in exist
      }

Current Error: System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpRequest' while attempting to activate 'CAWP.Api.Controllers.MvcDepency'.'

Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • You mean something like this? https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/ – spender Sep 07 '18 at 09:15

1 Answers1

0

Controllers already have access to the HttpRequest object in each of the methods via the base class. But it is only available once a method is called (for obvious reasons!). If you want to wrap it in your own class then you can do it in the OnActionExecuting override.

You can create a new MvcDepency class in OnActionExecuting and reference it in the code. As controllers are created per request you should be able to use a class variable to store the reference.

public class ValuesController : Controller
{
    private IMvcDepency _depency;

    public ValuesController()
    {
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        _depency = new MvcDepency(context.HttpContext.Request);

        base.OnActionExecuting(context);
    }

    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        var path = _depency.PathValue;

        return new string[] { "PathValue", path };
    }
}

This should result in the MvcDepency class having access to the HttpRequest object. You should add a factory class for your IMvcDepency interface to avoid the new in OnActionExecuting.

Simply Ged
  • 8,250
  • 11
  • 32
  • 40