且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

注射IOwinContext使用Web API和Ninject

更新时间:2023-02-24 12:02:18

免责声明:这是一个黑客。它的工作原理,但感觉很污秽。使用后果自负。

DISCLAIMER: This is a hack. It works, but it feels very unclean. Use at your peril.

在本质上,你可以创建一个OwinContextHolder级,将其绑定InRequestScope并使用DelegatingHandler来填充它的每个请求。事情是这样的:

In essence, you can create an OwinContextHolder class, bind it InRequestScope and use a DelegatingHandler to populate it on each request. Something like this:

public class OwinContextHolder
{
    public IOwinContext OwinContext { get; set; }
}

public class OwinContextHolderModule : NinjectModule
{
    public override void Load()
    {
        // Instead of a NinjectModule you can of course just register the service
        this.Kernel.Bind<OwinContextHolder>().ToSelf().InRequestScope();
    }
}

您委托的处理程序:

public class SetOwinContextHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var holder = request.GetDependencyScope().GetService(typeof(OwinContextHolder)) as OwinContextHolder;
        if (holder != null)
        {
            holder.OwinContext = request.GetOwinContext();
        }
        return base.SendAsync(request, cancellationToken);
    }
}

最后DelegatingHandler添加到您的启动类:

Finally add the DelegatingHandler to your Startup class:

public void Configuration(IAppBuilder app)
{
    var webApiConfiguration = new HttpConfiguration();
    webApiConfiguration.Routes.MapHttpRoute(...);

    webApiConfiguration.MessageHandlers.Add(new SetOwinContextHandler());

    app.UseNinjectMiddleware(CreateKernel);
    app.UseNinjectWebApi(webApiConfiguration);
}

您现在可以注入OwinContextHolder到您的类。

You can now inject OwinContextHolder into your classes.

请注意,如果你有从您的主机一个单独的程序你的API,你可能有InRequestScope默默不工作的问题(如,你每次请求一个没有错误的时间得到不同的对象)。如果你这样做,请参见 https://groups.google.com/forum/#​​!专题/ ninject / Wmy83BhhFz8

Note that if you have your API in a separate assembly from your host, you may have problems with InRequestScope silently not working (as in, you get a different object every time you request one and no errors). If you do, see https://groups.google.com/forum/#!topic/ninject/Wmy83BhhFz8.