asp.net mvc - unity.mvc4: how to get a reference -


i've setup unity in bootstrapper.cs of mvc application, working constructor injection on controllers...

my question when i'm in actionresult within controller need reference container created in bootstrapper.cs can use resolve classes me.

e.g:

public actionresult index() {     //-- container needs reference unity container     var testservice = container.resolve<itestservice>();     return view(testservice); } 

i need reference container

no don't. should never need reference container (or dependencyresolver) within application.

use constructor injection instead:

public class homecontroller : controller {     private readonly itestservice testservice;      // constructor     public homecontroller(itestservice testservice)     {         this.testservice = testservice;     }      public actionresult index()     {         return view(this.testservice);     } } 

since using mvc3 integration package unity, registered unity specific dependencyresolver in startup path of application. looks this:

dependencyresolver.setresolver(new unitydependencyresolver(container)); 

when you've done this, custom dependencyresolver delegate creation of controllers unity container , unity container able inject depdencies of constructor's of controllers.

the next thing should never letting views work , making them dependent on services. views should dumb , nothing more map data controller , transform them html (or json or whatever).

in other words, not pass on testservice view. calling testservice within view hides logic, makes view more complicated, , makes system hard test. since you're using itestservice abstraction, assume want able test code, testing view not easy (or @ least, not easy can test controller).

what should let controller call testservice , gather data needed view use. pass on data (perhaps combined in single class, view model) view.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -