RequestScope() and Kernel.Get<> in Ninject
If I define a binding in ninject with ReqeustScope()
, and then call Kernel.Get<T>
on that type outside开发者_Go百科 of a request what will the scope of the resolved object be?
If we study the StandardScopeCallbacks we can see that the callback for the request scope is the current HTTP context. The callback for a transient object is null. If you resolve a service outside of a request the current HTTP context is null. Thus, the scope is implicit transient as apparent of the following test.
[Test]
public void ServiceInRequestScopeIsImplicitTransientWhenHttpContextIsNull()
{
var kernel = new StandardKernel();
kernel.Bind<ServiceInRequestScope>().ToSelf().InRequestScope();
Assert.That(HttpContext.Current, Is.Null);
var service0 = kernel.Get<ServiceInRequestScope>();
var service1 = kernel.Get<ServiceInRequestScope>();
Assert.That(service0, Is.Not.SameAs(service1));
}
精彩评论