StructureMap 是一个非常灵巧的IOC框架,与asp.net MVC 更是很好的集成。
准备:
下载StructureMap,基本实例中只需要引用StructureMap.dll文件,并引用命名空间StructureMap
下面是我们需要使用IoC的示例代码,我们要创建TestController,希望通过IoC为TestController的构造函数提供Ants.Provider.ICacheProvider的实例对象。
Step1:
用StructureMapControllerFactory代替默认的DefaultControllerFactory,以及StructureMap的初始化,并在Application_Start()进行注册。
1.StructureMapControllerFactory代替默认的DefaultControllerFactory以及StructureMap的初始化
using System; using System.Web.Mvc; using StructureMap; namespace MvcWeb.Ioc { //用StructureMap接管MVC中的Controller的创建工作 public class StructureMapControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { if (controllerType == null) return null; try { return ObjectFactory.GetInstance(controllerType) as Controller; } catch (StructureMapException) { System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave()); throw; } } } //初始化StructureMap,注入相关对象 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.在Application_Start()进行注册
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); //初始化StructureMap MvcWeb.Ioc.StructureMapInitialize.Initialize(); //注册StructureMapControllerFactory以代替DefaultControllerFactory ControllerBuilder.Current.SetControllerFactory(new MvcWeb.Ioc.StructureMapControllerFactory()); }
Step2:构建TestControler
using System.Web.Mvc; namespace MvcWeb.Controllers { [HandleError] public class TestController : Controller { //_cache将会被自动注入 private readonly Ants.Provider.ICacheProvider _cache; public TestController(Ants.Provider.ICacheProvider cache) { this._cache = cache; } /********************************************** Test/Cache **********************************************/ public ActionResult Cache() { _cache.Insert("test", "Hello Word"); return Content(_cache.Get("test").ToString()); } } }Step3:直接浏览Test/Cache 就可以看到成功的显示“Hello World”.