Maxim Tkachenko
Maxim Tkachenko

Reputation: 5798

asp.net web api dependency resolver with ninject: BeginScope

I've created dependency resolver with ninject for asp.net web api using this article and it works fine. But I have two questions:

  1. what is BeginScope method required for? There is no this method in asp.net mvc dependency resolver and it works ok;
  2. what is purpose of kernel.BeginBlock() method? I've never used it.

Upvotes: 0

Views: 970

Answers (1)

Jeremy F
Jeremy F

Reputation: 467

Typically Ninject does not handle the disposal of created objects, instead the disposal is handled by the garbage collector when objects go out of scope. The problem with disposal by the garbage collector is that it is non-deterministic, we don't know when it will happen! This can be bad for scarce resources such as database connections.

The idea of BeginScope and Kernel.BeginBlock is much like the using() block in the C# language. It forces the cleanup of any objects created by Ninject at the end of the scope block. The disposal of these objects would then be deterministic and all objects would be as short lived as possible.

When it comes to ASP.NET MVC if you use the Ninject.MVC5 nuget package it will register an http module that disposes of all Ninject created types that are in Request Scope at the end of a request. As a result, creating and managing scope blocks inside your controllers is not required.

I believe the Ninject package for ASP.NET WebAPI would function in the same manner but sorry I have no experience with it.

I have considered these issues before, and an alternative approach is to inject your controllers with factories that create the disposable types you are trying to manage. Then in your controller construct the the resource yourself and control its lifetime with a normal using() block.

Upvotes: 3

Related Questions