Dependency Injection: ASP vNext. How it works?

Thus, in my CQRS-based web-based error tracking API, I will reorganize my code before developing and implementing unit tests (which must 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 introduced a dependency using

 services.AddSingleton<IBugCommandHandler, BugCommandHandler>(); 

My unit tests and manual integration tests work fine, as they did when I manually called this without DI.



How does the BugCommandHandler implementation now work as if it were called with the database context in its constructor (behind the scenes "magic")? What is his β€œprocess of achieving this?

I checked (not so) some source code in the Github repository, but cannot find where this could happen.

I might be missing out on something important, or it might just be hidden, as it is still in pre-release.

+4
c # dependency-injection asp.net-core entity-framework cqrs
source share
1 answer
  • When you call AddSingleton , the type registration is stored in the DI container. The code is here .
  • When you add MVC services by calling AddMvc , they are added to the same DI container as type in step 1. The magic happens. This is how the container is transferred to the stack and divided between the components.
  • When MVC activates your controller, it will instantiate using types in the container; what is going on here . In the end, this code is called. He will try to resolve this service and all its dependencies using registration in the container.

In your particular case, you will also need a BugContext to register.

You may find this article useful, which I wrote some time ago about DI in ASP.NET 5. It is a bit dated 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 know what is going on, take a look at another article that I wrote about debugging framework code in ASP.NET 5. You can log into 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 script, you will need sources for DependencyInjection and MVC .

+6
source share

All Articles