简体   繁体   中英

ASP.NET Core MVC inject per request

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'.'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM