【问题标题】:Using Ninjects InRequestScope() when selfhosting Web API自托管 Web API 时使用 Ninjects InRequestScope()
【发布时间】:2012-04-14 22:53:50
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    我建议为控制器实现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

    【讨论】:

    • 看起来现在有一个扩展 Ninject.Web.WebAPI 支持这个,但目前没有在 ninject.org/extensions.html 列出?该页面是否已过时并且应该重定向到其他地方,还是只需要更新?如果是后者,该页面的来源是否在 github 上,我可以提交拉取请求来提供帮助吗?非常感谢,雷莫!!你和 ninject rock :)
    • 以这种方式使用命名范围不支持 ActionFilters
    猜你喜欢
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2015-01-09
    相关资源
    最近更新 更多