如何将 Owin 上下文传递给注入 Api 控制器的 Repo [英] How to pass Owin context to a Repo being injected into Api controller

查看:25
本文介绍了如何将 Owin 上下文传递给注入 Api 控制器的 Repo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MVC WebApi owin(软托管)项目,它使用 Unity 来解决控制器依赖项

看起来像这样

public class PacientaiController : ODataController{私有只读 IEntityRepo回购;public PacientaiController(IEntityRepo repo){this.repo = 回购;}

我试图解决的问题 - 是如何将OwinContex"传递到 Repo 中.

public class PacientasEntityRepo:IEntityRepo,IDisposable{公共PacientasEntityRepo(IOwinContext ctx){…………

如果我尝试在 Startup.cs

中像这样注册它

Container.RegisterType(new InjectionFactory(o => HttpContext.Current.GetOwinContext()));

我得到一个空引用,说 HttpContext.Current 是 NULL

这里的主要思想是将当前经过身份验证的用户传递给 repo,因为 Repo 托管查询数据库的逻辑,具体取决于用户.(假设用户是Admin,则返回此数据,如果用户是guest - 返回此数据)

重点是 - 这是一个自我主持人!

解决方案

先抛开你为什么有这个设计,专注于问题:注入IOwinContext:

您也可以使用 GetOwinContext 方法从 HttpRequestMessage 实例中获取它,但是您还需要以某种方式获取 HttpRequestMessage.

Unity 不支持开箱即用地注入 HttpRequestMessage,但您可以使用自定义 DelegatingHandler 将当前 HttpRequestMessage 存储在容器如下所述:使用 Autofac 将 WebAPI UrlHelper 注入服务

链接的问题是关于 Autofac,但您可以将其转移到 Unity 中使用:

CurrentRequestCurrentRequestHandler 可以从 Andrew Davey 使用a> 的答案是:

公共类 CurrentRequest{公共 HttpRequestMessage 值 { 获取;放;}}公共类 CurrentRequestHandler : DelegatingHandler{受保护的异步覆盖 System.Threading.Tasks.TaskSendAsync(HttpRequestMessage 请求,System.Threading.CancellationToken 取消令牌){var scope = request.GetDependencyScope();var currentRequest = (CurrentRequest)scope.GetService(typeof(CurrentRequest));currentRequest.Value = 请求;返回等待 base.SendAsync(请求,取消令牌);}}

然后你只需要注册DelegatingHandler:

httpConfiguration.MessageHandlers.Insert(0, new CurrentRequestHandler());

并在容器中注册CurrentRequestIOwinContext

container.RegisterType(新的 HierarchicalLifetimeManager());container.RegisterType(新的 HierarchicalLifetimeManager(),new InjectionFactory(c => c.Resolve().Value.GetOwinContext()));httpConfiguration.DependencyResolver = new UnityHierarchicalDependencyResolver(container);

除了自定义委托处理程序之外,还有其他地方可以连接到 Web.API 以捕获 HttpRequestMessage 例如,您可以创建自己的 IHttpControllerActivator 并使用 ExecuteAsync 方法如下所述:ASP 中的依赖注入.NET Web API 2

I've got a MVC WebApi owin (soft hosted) project, that uses Unity for resolving controller dependencies

which look like this

public class PacientaiController : ODataController
    {
        private readonly IEntityRepo<Ent.Pacientas> repo;

        public PacientaiController(IEntityRepo<Ent.Pacientas> repo)
        {
            this.repo = repo;
        }

the problem I'm trying to solve - is how do I pass 'OwinContex' into a Repo.

public class PacientasEntityRepo:IEntityRepo<Pacientas>,IDisposable
    {
        public PacientasEntityRepo(IOwinContext ctx)
        {
        .........

If I try to register it like this in the Startup.cs

Container.RegisterType<IOwinContext>(new InjectionFactory(o => HttpContext.Current.GetOwinContext()));

I get a null ref, saying that HttpContext.Current is NULL

The main idea here, is to pass the currently authenticated user to the repo, because Repo host the Logic for querying the Database, depending on the user. (say if the user is Admin, then return this data, if the user is guest - return this data)

The point being - that this is a self Host !

解决方案

Lets put aside why you have this design and concentrate to the problem: injecting the IOwinContext:

you can also get it from a HttpRequestMessage instance with the GetOwinContext method, however you also need to get a HttpRequestMessage somehow.

Unity does not support injection of the HttpRequestMessage out of the box but you can use a custom DelegatingHandler which stores the current HttpRequestMessage in the container as described here: Inject WebAPI UrlHelper into service using Autofac

The linked question is about Autofac but you can transfer it for work with Unity:

The CurrentRequest and the CurrentRequestHandler can be used from Andrew Davey's answer as it is:

public class CurrentRequest
{
    public HttpRequestMessage Value { get; set; }
}

public class CurrentRequestHandler : DelegatingHandler
{
    protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var scope = request.GetDependencyScope();
        var currentRequest = (CurrentRequest)scope.GetService(typeof(CurrentRequest));
        currentRequest.Value = request;
        return await base.SendAsync(request, cancellationToken);
    }
}

Then you just need to register the DelegatingHandler with:

httpConfiguration.MessageHandlers.Insert(0, new CurrentRequestHandler());

And register the CurrentRequest and IOwinContext in the container

container.RegisterType<CurrentRequest>(
            new HierarchicalLifetimeManager());

container.RegisterType<IOwinContext>(
    new HierarchicalLifetimeManager(),
    new InjectionFactory(c => c.Resolve<CurrentRequest>().Value.GetOwinContext()));

httpConfiguration.DependencyResolver = new UnityHierarchicalDependencyResolver(container);

Beside the custom delegation handler there are other places to hook into Web.API to capture the HttpRequestMessage for example you can create your own IHttpControllerActivator and use the ExecuteAsync method as described here: Dependency Injection in ASP.NET Web API 2

这篇关于如何将 Owin 上下文传递给注入 Api 控制器的 Repo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆