asp.net mvc - Dependency injection in MVC + Web API, without interfaces of repository in controller constructor -


i going use simpleinjector in mvc.5 application webapi.2

some methods of mvc controllers create objects of repositories crud operations. common approach on internet using interface of repository in mvc controller, like:

public class dashboardcontroller : controller {     private readonly idashboardrepository _repository;      public dashboardcontroller (idashboardrepository repository) {         _repository = repository;     }      [httppost]     public jsondata getinfo()     {         return _repository.getinfo();     } ... 

similar approach recommended webapi

however not pass idashboardrepository constructor of controller because of such reasons: sure never mock implementation of repository. not need separate public interface repository (current code base has no these interfaces , i'll need change lot of files add them).

my repositories like:

public class dashboardfunc : basefunc {     public dashboardfunc(iapplicationstateprovider sp) :         base (sp)     {     }      public dashboarddata getinfo()     {         ... 

i use such code in controllers of mvc:

public class dashboardcontroller : controller {

    public dashboardcontroller () {     }      [httppost]     public jsondata getinfo()     {         dashboardfunc dashboard = global.mvccontainer.getinstance<dashboardfunc>();         return common.tojson(dashboard.getinfo());     } 

the same approach webapi controllers. difference dashboardfunc dashboard = global.webapicontainer.getinstance();

is modification (not using interface of repository in controller) of standard approach ok? there potential issues can arise in future can lead architecture change?

thank you!

prevent falling on calling global.mvccontainer.getinstance or other form of service location anti-pattern. there lot of downsides this, if don't want test code. downsides of using (among others):

  • you lose ability container change given implementation you; makes application less flexible.
  • you lose ability container diagnose complete object graph you.
  • you lose ability verify configuration during app start or using integration test.
  • you lose ability spot class's dependencies looking @ single line of code (the constructor).

so when don't need interface, advice still use constructor injection , following:

public class dashboardcontroller : controller {     private readonly dashboardfunc dashboard;     public dashboardcontroller(dashboardfunc dashboard) {         this.dashboard = dashboard;     }      [httppost]     public jsondata getinfo() {         return common.tojson(this.dashboard.getinfo());     } } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -