StructureMap 作为 ASP.NET MVC 的 DI 框架的使用实例
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的初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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()进行注册
1
2
3
4
5
6
7
8
9
10
11
12
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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()); } } } |