c# - 自托管 Web API 时使用 Ninject InRequestScope()

标签 c# .net asp.net-mvc-3 ninject asp.net-web-api

我正在使用自托管方法创建一个具有 ASP.NET Web API 接口(interface)的应用程序。我想使用类似于 MVC3 提供的 InRequestScope() 的范围。当我在 IIS 上托管 Web API 应用程序时,这似乎受到 Ninject.Extension.WebAPI 的支持。但是,当自托管 WebAPI 时,我会在创建绑定(bind) InRequestScope() 时获得一个新实例。当我自行托管 Web API 时,有什么方法可以使用此范围?

最佳答案

您可以使用 NamedScope 扩展来定义 Controller 定义范围并将该范围用于请求范围内的所有内容。最好使用此定义的约定:

const string ControllerScope = "ControllerScope"; 
kernel.Bind(x => x.FromThisAssembly()
                  .SelectAllClasses().InheritedFrom<ApiController>()
                  .BindToSelf()
                  .Configure(b => b.DefinesNamedScope(ControllerScope)));

kernel.Bind<IMyComponent>().To<MyComponent>().InNamedScope(ControllerScope);

我建议为 Controller 实现INotifyWhenDisposed,以便在请求后立即释放请求范围内的对象。例如。通过派生自以下类而不是 ApiController

public abstract class NinjectApiController : ApiController, INotifyWhenDisposed
{
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        this.IsDisposed = true;
        this.Disposed(this, EventArgs.Empty);
    }

    public bool IsDisposed
    {
        get;
        private set;
    }

    public event EventHandler Disposed;
}

我会尝试在未来几周内为 WebAPI 自托管提供扩展。

编辑:

自托管支持现在由 Ninject.Web.WebApi.Selfhosting 提供 https://nuget.org/packages/Ninject.Web.WebApi.Selfhost/3.0.2-unstable-0

示例:https://github.com/ninject/Ninject.Web.WebApi/tree/master/src/Ninject.Web.WebApi.Selfhost

关于c# - 自托管 Web API 时使用 Ninject InRequestScope(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158015/

相关文章:

c# - 是否可以调用参数为 'lambda expression' 的方法?

c# - C#中的开源视频手势识别库

css - 在 MVC 3 Razor 中垂直对齐文本框

c# - 我可以将 C# 变量分配给 javascript 函数的 return 语句吗?

c# - 带有自定义控件的 Xamarin.Android 通知在 API26 中不起作用

c# - 在 WPF 应用程序中使用 C# 确定位图中像素的颜色

c# - 将 GridView 绑定(bind)到列表

c# - 使用选定的 Xpath 和 for 循环删除 XML

.net - .NET 的 AWGN 生成器

asp.net-mvc - 自定义格式化日期的 MVC3 不显眼的日期验证