Structuremap is a very clever IOC framework, which is well integrated with Asp.net MVC.
Preparation:
Download structuremap. In the basic instance, you only need to reference the structuremap. dll file and reference the namespace structuremap.
The following is an example of IOC.CodeWe want to create testcontroller and provide the ants. provider. icacheprovider instance object for the testcontroller constructor through IOC.
Step 1:
Use structuremapcontrollerfactory to replace the default defaultcontrollerfactory, initialize structuremap, and register application_start.
1. structuremapcontrollerfactory replaces the default defaultcontrollerfactory and structuremap initialization.
Using system; using system. web. MVC; using structuremap; namespace mvcweb. IOC {// use structuremap to take over the Controller creation in MVC. Public class structuremapcontrollerfactory: defaultcontrollerfactory {protected override icontroller getcontrollerinstance (system. web. routing. requestcontext, type controllertype) {If (controllertype = NULL) return NULL; try {return objectfactory. getinstance (controllertype) as controller;} catch (structuremapexception) {system. diagnostics. debug. writeline (objectfactory. whatdoihave (); throw ;}}// initialize structuremap and inject the relevant object public class structuremapinitialize {public static void initialize () {objectfactory. initialize (x => {X. for <ants. provider. iauthenticateprovider> (). singleton (). use <ants. provider. customauthenticateprovider> (); X. for <ants. provider. icacheprovider> (). singleton (). use <ants. provider. aspnetcacheprovider> ();});}}}
2. Register in application_start ()
Protected void application_start () {arearegistration. registerallareas (); registerroutes (routetable. routes); // initialize structuremap mvcweb. IOC. structuremapinitialize. initialize (); // register structuremapcontrollerfactory to replace defacontrocontrollerfactory controllerbuilder. current. setcontrollerfactory (New mvcweb. IOC. structuremapcontrollerfactory ());}
Step 2:Construct testcontroler
Using system. web. MVC; namespace mvcweb. controllers {[handleerror] public class testcontroller: controller {// _ cache will be automatically injected into private readonly ants. provider. icacheprovider _ cache; Public testcontroller (ants. provider. icacheprovider cache) {This. _ cache = cache ;} /*************************************** ****************************** * **************/Public actionresult cache () {_ cache. insert ("test", "Hello word"); Return content (_ cache. get ("test "). tostring ());}}}
Step 3: View test/cache to view the successful display of "Hello World ".