我正在使用自托管方法创建一个具有 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/