Joel Lord
Joel Lord

Reputation: 107

Dependency Injection: ASP vNext. How is this working?

So in my CQRS-based bug-tracking web-API, I am refactoring my code before progressing and implementing unit tests (which, admittedly, should have come first); I have this class and constructor:

public class BugCommandHandler : IBugCommandHandler
{
    private BugContext db;

    public BugCommandHandler(BugContext bugContext)
    {
        db = bugContext;
    }

    //Interface implementation
}

In my controller, I have this:

public class BugsController : Controller
{
    private IBugCommandHandler commandHandler;
    private BugContext db;

    public BugsController(BugContext bugContext, IBugCommandHandler bugCommandHandler)
    {
        db = bugContext;
        commandHandler = bugCommandHandler;
    }
}

And, finally, in my Startup class, I have injected the dependency with

services.AddSingleton<IBugCommandHandler, BugCommandHandler>();

My Unit Tests and manual Integration Tests are all working fine as they were when I was manually calling this without DI.

How does the BugCommandHandler implementation now work as though it has been called with the database context in its constructor (behind the scenes 'magic')? What is its' process to achieve this?

I've checked out (not like that) some of the source code in the Github repo, but can't really find where this may be happening.
I may be overlooking something crucial, or it may just be well-hidden as it is still in pre-release.

Upvotes: 4

Views: 603

Answers (1)

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

  1. When you call AddSingleton, the type registration is stored in the DI container. The code is here.
  2. When you add the MVC services by calling AddMvc, they are added to the same DI container as the type(s) at step 1. The magic happens here. That's how the container is passed up the stack and shared between components.
  3. When MVC activates your controller, it will create an instance using the types in the container; that happens here. Eventually, this code is called. It will try to resolve that service and all its dependencies using the registrations in the container.

In your particular case, you also need BugContext to be registered.

You might find useful this article that I wrote a while ago about DI in ASP.NET 5. It is a little outdated in terms of code but the principles are the same: http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx

Also, if you really want to see what happens, take a look at the other article that I wrote about debugging the framework code in ASP.NET 5. You can step in MVC and see the exact code path: http://blogs.msdn.com/b/webdev/archive/2015/02/06/debugging-asp-net-5-framework-code-using-visual-studio-2015.aspx . If you want to see all the code in your scenario you will need the sources for DependencyInjection and MVC.

Upvotes: 6

Related Questions