StructMap实现对MVC4.0 WebAPI的依赖注入

MVC4.0 WebAPI的依赖注入不同于对MVC的注入,MVC的注入可以通过重写构造Controller 类解决,而WebAPI的controller继承于ApiController,原理不一样。关于IOC的使用以及各控制反转组件,在这里就不一一介绍了,主要的如:Microsoft.Practices.Unity(微软)、Ninject、Autofac、StructMap等,这里拿StructMap举例,主要实现对接口的注入。对于IOC不了解的可先了解,详细的就不多叙了。

通过国外某篇文章的解决方案,现整理主要代码如下:

  1 /// <summary>
  2     /// IOC 引导启动类
  3     /// </summary>
  4     public static class Bootstrapper
  5     {
  6         public static void Start()
  7         {
  8             var container = (IContainer)Ioc.Initialize();
  9             //  var container = ObjectFactory.Container;
 10             GlobalConfiguration.Configuration.DependencyResolver = new SmDependencyResolver(container);
 11         }
 12     }
 13 
 14     /// <summary>
 15     /// IOC初始化方法
 16     /// </summary>
 17     public static class Ioc
 18     {
 19         public static IContainer Initialize()
 20         {
 21             ObjectFactory.Initialize(x =>
 22             {
 23                 //通过StructureMap自动扫描所有符合条件项
 24                 x.Scan(scan =>
 25                 {
 26                     scan.TheCallingAssembly();
 27                     scan.WithDefaultConventions();
 28                 });
 29                 //x.For<IProductRepository>().Use<ProductRepository>();//这里是手动,二者取其一
 30             });
 31             return ObjectFactory.Container;
 32         }
 33     }
 34 
 35     /// <summary>
 36     /// StructureMap 服务类
 37     /// </summary>
 38     public class StructureMapScope : IDependencyScope
 39     {
 40         protected IContainer Container;
 41 
 42         public StructureMapScope(IContainer container)
 43         {
 44             Container = container;
 45         }
 46 
 47         public void Dispose()
 48         {
 49             IDisposable disposable = (IDisposable)Container;
 50             if (disposable != null)
 51             {
 52                 disposable.Dispose();
 53             }
 54             Container = null;
 55         }
 56 
 57         public object GetService(Type serviceType)
 58         {
 59             if (serviceType == null)
 60             {
 61                 return null;
 62             }
 63             try
 64             {
 65                 if (serviceType.IsAbstract || serviceType.IsInterface)
 66                     return Container.TryGetInstance(serviceType);
 67 
 68                 return Container.GetInstance(serviceType);
 69             }
 70             catch
 71             {
 72                 return null;
 73             }
 74         }
 75 
 76         public IEnumerable<object> GetServices(Type serviceType)
 77         {
 78             return Container.GetAllInstances<object>().Where(s => s.GetType() == serviceType);
 79         }
 80     }
 81 
 82     /// <summary>
 83     /// 解决方案
 84     /// </summary>
 85     public class SmDependencyResolver : StructureMapScope, IDependencyResolver
 86     {
 87         private IContainer _container;
 88 
 89         public SmDependencyResolver(IContainer container)
 90             : base(container)
 91         {
 92             _container = container;
 93         }
 94 
 95         public IDependencyScope BeginScope()
 96         {
 97             _container = (IContainer)Ioc.Initialize();
 98             return new StructureMapScope(_container);
 99         }
100     }

然后在Global.asax.cs文件中加入对StructMap的启动

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            Bootstrapper.Start();//IOC启动
        }

 

接下来在Controller里实现StructMap应用:

 1 public class ProductController : ApiController
 2     {
 3         #region 接口注入
 4         private readonly IProductDal db;
 5         public ProductController(IProductDal repository)
 6         {
 7             if (repository == null)
 8             {
 9                 throw new ArgumentNullException("repository");
10             }
11             this.db = repository;
12         }
13         #endregion
14        
15         [HttpGet]
16         public IList<ProductEntity> GetList()
17         {            
18             return db.GetProductList();
19         }
20     }

 

 

 

posted @ 2012-09-27 10:05  白云任去留  阅读(4270)  评论(3编辑  收藏  举报