c# - Dependency Injection: ASP vNext. How is this working? -


so in cqrs-based bug-tracking web-api, refactoring code before progressing , implementing unit tests (which, admittedly, should have come first); have class , constructor:

public class bugcommandhandler : ibugcommandhandler {     private bugcontext db;      public bugcommandhandler(bugcontext bugcontext)     {         db = bugcontext;     }      //interface implementation } 

in controller, 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 startup class, have injected dependency with

services.addsingleton<ibugcommandhandler, bugcommandhandler>(); 

my unit tests , manual integration tests working fine when manually calling without di.

how bugcommandhandler implementation work though has been called database context in constructor (behind scenes 'magic')? its' process achieve this?

i've checked out (not that) of source code in github repo, can't find may happening.
may overlooking crucial, or may well-hidden still in pre-release.

  1. when call addsingleton, type registration stored in di container. code here.
  2. when add mvc services calling addmvc, added same di container type(s) @ step 1. magic happens here. that's how container passed stack , shared between components.
  3. when mvc activates controller, create instance using types in container; happens here. eventually, this code called. try resolve service , dependencies using registrations in container.

in particular case, need bugcontext registered.

you might find useful article wrote while ago di in asp.net 5. little outdated in terms of code principles same: http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx

also, if want see happens, take @ other article wrote debugging framework code in asp.net 5. can step in mvc , see 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 want see code in scenario need sources dependencyinjection , mvc.


Popular posts from this blog