Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 of a request what will the scope of the resolved object be?

like image 479
kay.one Avatar asked Jun 08 '11 03:06

kay.one


1 Answers

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));
}
like image 156
mrydengren Avatar answered Sep 20 '22 00:09

mrydengren