每个请求都会插入ASP.NET Core MVC

时间:2018-09-07 09:09:59

标签: c# unit-testing .net-core tdd moq

我期待在.Net Core中为每个请求注入RequestContext。在服务集合中。

有人尝试了8年。前。 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;
    }
}

并在启动时将其注入到某处,如下所示:

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

或在如下所示的OnActionExecuting中:

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
      }

当前错误: System.InvalidOperationException:“尝试激活“ CAWP.Api.Controllers.MvcDepency”时,无法解析类型为“ Microsoft.AspNetCore.Http.HttpRequest”的服务。”

1 个答案:

答案 0 :(得分:0)

控制器已经可以通过基类访问每个方法中的HttpRequest对象。但是它仅在调用方法后才可用(出于明显的原因!)。如果您要将其包装在自己的类中,则可以在OnActionExecuting替代中进行。

您可以在MvcDepency中创建一个新的OnActionExecuting类,并在代码中引用它。根据请求创建控制器后,您应该可以使用类变量来存储引用。

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 };
    }
}

这应该导致MvcDepency类可以访问HttpRequest对象。 您应该为IMvcDepency接口添加一个工厂类,以避免new中的OnActionExecuting