C# Dependency Injection – Multiple Instances or Single InRequestScope

asp.net-mvccdependency-injectionninject

I'm trying to understand what happens with dependencies (Ninject) when a same Interface in injected in multiple classes. I am specifying InRequestScope for my bindings so as I understand there should always be a single instance of let's say my IUnitOfWork in a single HttpRequest.

Is there a way I can check how many instances of IUnitOfWork are currently open inside one HttpRequest – which would confirm or deny my question here.

I made a simple mock sample of how I'm using it and what my question is.

The question is – in a single HttpRequest will there be two instances of IUnitOfWork or only one?

I have a Unit of work which implements an interface and some methods.

public interface IUnitOfWork : IDisposable
{
    string GetItem(string what);
    string GetAllItems();
}

public class UnitOfWork : IUnitOfWork
{
    public string GetAllItems()
    {
        return "This is something different...";
    }

    public string GetItem(string what)
    {
        return "Actual item for " + what + " is Beer";
    }

    public void Dispose()
    {
        // Dispose any contexts etc.
    }
}

I also have a Service class which implements an Interface and is consumed by a Controller. This service takes an IUnitOfWork through a constructor.

public interface IService
{
    string ServeMe(string what);
}
public class Service : IService
{
    private readonly IUnitOfWork _unitOfWork;
    public Service(IUnitOfWork unitOfWork)
    {
        this._unitOfWork = unitOfWork;
    }

    public string ServeMe(string what)
    {
        return "Served you some: " + _unitOfWork.GetItem(what);
    }
}

My controller takes two parameters through its constructor – IUnitOfWork and IService.

Please don't mind the architectural decision, I know I should only inject IService in my controller, but this is the easiest way to show what my question is.

public class HomeController : Controller
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IService _service;
    public HomeController(IUnitOfWork unitOfWork,
                            IService service)
    {
        this._unitOfWork = unitOfWork;
        this._service = service;
    }

    public ActionResult Index()
    {
        ViewBag.Item = _unitOfWork.GetAllItems();
        return View();
    }

    public ActionResult Serve()
    {
        ViewBag.Served = _service.ServeMe("a drink");
        return View();
    }
}

And finally I'm using Ninject for my DI needs. This is how I bind both IUnitOfWork and IService.

kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IService>().To<Service>().InRequestScope();

Best Answer

In theory, you should only get one instance, unless you made an error in your DI-registration.

To check what's happening, just put a breakpoint inside the UnitOfWork-class' constructor. Each time it hits, a new UnitOfWork is constructed.