1. IOC:控制反转,是一种设计模式。一层含义是控制权的转移:由传统的在程序中控制依赖转移到由容器来控制;第二层是依赖注入:将相互依赖的对象分离,在spring配置文件中描述他们的依赖关系。他们的依赖关系只在使用的时候才建立。
  2.  
  3. AOP:面向切面,是一种编程思想,OOP的延续。将系统中非核心的业务提取出来,进行单独处理。比如事务、日志和安全等。

一.配置与注册Services和Repositories

首先我们告诉StructureMap,我们需要注入的是什么,本系统中需要注册的是Services和Repositories,分别注入到 Controller和Service。下面是具体写法,为什么这么写,不必较真,写法是StructureMap提供给我们的,使用就好了。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using StructureMap;
  7.  
  8. namespace TYStudioDemo.StructureMap
  9. {
  10. public class BootStrapper
  11. {
  12. public static void ConfigureStructureMap()
  13. {
  14. ObjectFactory.Configure(x =>
  15. {
  16. x.AddRegistry(new TYStudioDemoStructureMapRegistry());
  17. x.Scan(scanner =>
  18. {
  19. scanner.Assembly("TYStudioDemo.Services");
  20. scanner.Assembly("TYStudioDemo.Repositories");
  21. });
  22. });
  23. }
  24. }
  25. }

上面的代码告诉了StructureMap去哪里找我们的Service和Repositories。同时 TYStudioDemoStructureMapRegistry这个类告诉了StructureMap该用哪个类去实例化我们的接口,下面是 TYStudioDemoStructureMapRegistry的代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using StructureMap.Configuration.DSL;
  7. using TYStudioDemo.Models;
  8. using TYStudioDemo.DTO;
  9. using TYStudioDemo.Interfaces;
  10. using TYStudioDemo.Services;
  11. using TYStudioDemo.Repositories;
  12.  
  13. namespace TYStudioDemo.StructureMap
  14. {
  15. public class TYStudioDemoStructureMapRegistry : Registry
  16. {
  17. //注册接口实际使用的实现类
  18. public TYStudioDemoStructureMapRegistry()
  19. {
  20. SelectConstructor<TYEntities>(() => new TYEntities());
  21.  
  22. //Exception Handle
  23. For<ITYExceptionService>().Use<TYExceptionService>();
  24.  
  25. //Services
  26. For(typeof(ISupplierService)).Use(typeof(SupplierService));
  27.  
  28. //Repositories
  29. For(typeof(ISupplierRepository<>)).Use(typeof(SupplierRepository));
  30. For(typeof(IProductRepository<>)).Use(typeof(ProductRepository));
  31. }
  32. }
  33. }

现在我们已经配置了StructureMap并且注册了Service和Repository,接下来该告诉系统去使用StructureMap去实例化我们的Controller。

二.创建Controller Factory

既然使用了依赖注入,Controller的实例化当然不能再用系统本身的了,所以我们需要创建一个ControllerFactory:TYStudioDemoStructureMapControllerFactory。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Web.Mvc;
  7. using StructureMap;
  8.  
  9. namespace TYStudioDemo.StructureMap
  10. {
  11. public class TYStudioDemoStructureMapControllerFactory : DefaultControllerFactory
  12. {
  13. protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, System.Type controllerType)
  14. {
  15. if (controllerType != null)
  16. {
  17. Controller c = ObjectFactory.GetInstance(controllerType) as Controller;
  18. //当返回一个错误页面,View一级异常会被触发
  19. c.ActionInvoker = new ErrorHandlingActionInvoker(new HandleErrorAttribute());
  20. return c;
  21. }
  22. else
  23. return null;
  24. }
  25. }
  26. }

TYStudioDemoStructureMapControllerFactory继承自 DefaultControllerFactory,DefaultControllerFactory是MVC默认的Controller Factory,然后重新器获得Controller实例的方法,由StructureMap的ObjectFactory来创建实 例,StructureMap会帮我们把Controller构造函数中的参数实例化。 上面的ErrorHandlingActionInvoker方法:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Mvc;
  6.  
  7. namespace TYStudioDemo.StructureMap
  8. {
  9. public class ErrorHandlingActionInvoker : ControllerActionInvoker
  10. {
  11. private readonly IExceptionFilter filter;
  12.  
  13. public ErrorHandlingActionInvoker(IExceptionFilter filter)
  14. {
  15. if (filter == null)
  16. throw new ArgumentNullException("Exception filter is missing");
  17.  
  18. this.filter = filter;
  19. }
  20.  
  21. protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDes criptor actionDes criptor)
  22. {
  23. var filterInfo = base.GetFilters(controllerContext, actionDes criptor);
  24. filterInfo.ExceptionFilters.Add(this.filter);
  25. return filterInfo;
  26. }
  27. }
  28. }

Controller Factory创建ok。但是这样系统是不会使用我们自己的Controller Factory的,所以需要通知一下MVC系统。

三.配置Global.asax文件

在Application_Start()方法中也就是项目启动的时候注册StructureMap并通知系统使用我们自己的Controller Factory进行实例化Controller。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Http;
  6. using System.Web.Mvc;
  7. using System.Web.Optimization;
  8. using System.Web.Routing;
  9. using TYStudioDemo.StructureMap;
  10.  
  11. namespace TYStudioDemo.WebUI
  12. {
  13. // Note: For instructions on enabling IIS6 or IIS7 classic mode,
  14. // visit http://go.microsoft.com/?LinkId=9394801
  15.  
  16. public class MvcApplication : System.Web.HttpApplication
  17. {
  18. protected void Application_Start()
  19. {
  20. AreaRegistration.RegisterAllAreas();
  21.  
  22. WebApiConfig.Register(GlobalConfiguration.Configuration);
  23. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  24. RouteConfig.RegisterRoutes(RouteTable.Routes);
  25. BundleConfig.RegisterBundles(BundleTable.Bundles);
  26. AuthConfig.RegisterAuth();
  27.  
  28. //注册StructureMap
  29. BootStrapper.ConfigureStructureMap();
  30.  
  31. //通过StructureMap返回Controller实例,通过构造器注入
  32. ControllerBuilder.Current.SetControllerFactory(new TYStudioDemoStructureMapControllerFactory());
  33. }
  34.  
  35. protected void Application_EndRequest(object sender, EventArgs e)
  36. {
  37. TYStudioDemo.Models.TYEntities.Cleanup();
  38. }
  39. }
  40. }

ok,到此StructureMap的配置就全部完成了,接下来我们该怎么使用它呢。 文章开头已经告诉大家了我们使用Constructor构造器的方式进行依赖注入。 Controller的写法 既然是构造器就要写构造函数了,见下面写法:

  1. ISupplierService _supplierService;
  2.  
  3. public SupplierController(ITYExceptionService tyExceptionService,
  4. ISupplierService supplierService)
  5. {
  6. _tyExceptionService = tyExceptionService;
  7. _supplierService = supplierService;
  8.  
  9. }

在构造方法中加入我们要注入的Service接口,然后StructureMap就会根据上面TYStudioDemoStructureMapRegistry的配置去创建我们需要实例化的service对象了。 同样向Service中注入Repository的写法是一样的:

  1. ISupplierRepository<Supplier> _supplierRepository;
  2. IProductRepository<Product> _productRepository;
  3.  
  4. public SupplierService(ISupplierRepository<Supplier> supplierRepotitory,
  5. IProductRepository<Product> productRepository)
  6. {
  7. _supplierRepository = supplierRepotitory;
  8. _productRepository = productRepository;
  9. }

至此StructureMap配置与使用就全部完成了。

总结:

我们发现,我们的参数都是接口类型了,这样的好处就是将来对ISupplierService的实现不一样了,我们只需要重写写一个 ISupplierService的实现了,并修改TYStudioDemoStructureMapRegistry使 ISupplierService使用新的实现类,就可以了。因为我们使用的都是接口所以方法和参数都是固定的,所以呢~~ Controller中不用修改任何代码,同理Service也是一样的。这样就充分的降低了代码之间的耦合度。

StructureMap依赖注入的更多相关文章

  1. MVC使用StructureMap实现依赖注入Dependency Injection

    使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controll ...

  2. DI 依赖注入之StructureMap框架

    DI  依赖注入之StructureMap框架 一.简叙: structureMap只是DI框架中的其中之一. 二.安装及使用: 1.懒人方法: 使用MVC5项目时,可以直接在nuget程序包中安装S ...

  3. ABP(现代ASP.NET样板开发框架)系列之6、ABP依赖注入

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之6.ABP依赖注入 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)” ...

  4. ABP框架 - 依赖注入

    文档目录 本节内容: 什么是依赖注入 传统方式的问题 解决方案 构造器注入模式 属性注入模式 依赖注入框架 ABP 依赖注入基础 注册依赖 约定注入 辅助接口 自定义/直接 注册 使用IocManag ...

  5. Unity依赖注入使用详解

    写在前面 构造器注入 Dependency属性注入 InjectionMethod方法注入 非泛型注入 标识键 ContainerControlledLifetimeManager单例 Unity注册 ...

  6. ABP理论学习之依赖注入

    返回总目录 本篇目录 什么是依赖注入 传统方式产生的问题 解决办法 依赖注入框架 ABP中的依赖注入基础设施 注册 解析 其他 ASP.NET MVC和ASP.NET Web API集成 最后提示 什 ...

  7. # ASP.NET Core依赖注入解读&使用Autofac替代实现

    标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...

  8. 基于DDD的.NET开发框架 - ABP依赖注入

    返回ABP系列 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...

  9. TypeC一个微软开发的超简单.NET依赖注入/IoC容器

    控制反转(IoC,Inversion of Control)是由Martin Fowler总结出来的一种设计模式,用来减少代码间的耦合.一般而言,控制反转分为依赖注入(Dependency Injec ...

随机推荐

  1. SpringBoot yml properties文件

    一.在SpringBoot实现属性注入: 1).添加pom依赖jar包: 1 <!-- 支持 @ConfigurationProperties 注解 --> 2 <!-- https ...

  2. Python repr() 函数

    Python repr() 函数  Python 内置函数 描述 repr() 函数将对象转化为供解释器读取的形式. 语法 以下是 repr() 方法的语法: repr(object) 参数 obje ...

  3. Python print() 函数

    Python print() 函数  Python 内置函数 描述 print() 方法用于打印输出,最常见的一个函数. print 在 Python3.x 是一个函数,但在 Python2.x 版本 ...

  4. 在c#中设置Excel格式

    生成excel的时候有时候需要设置单元格的一些属性,可以参考一下: range.NumberFormatLocal = "@"; //设置单元格格式为文本 ange.get_Ran ...

  5. html&css精华总结

    1.标题标签 h标签 2.段落标签 p 3.换行 br 4.空格   5.大于号,小于号 > < 6.双引号 " 7.版权符号 © 8.注册符 ® --------------- ...

  6. mybatis sql语句符号问题

    写sql语句<或>不能直接写,而应写作<或>,不然项目不能正常编译启动

  7. git设置别名alias

    每次用git拉去版本库都很烦,特别是要从非origin源,非master分支, 例如 git pull gitlab mybranch ,这样很蛋疼. 1.写个sh去处理 2.可以通过git的别名设置 ...

  8. 源码安装php时出现Sorry, I cannot run apxs. Possible reasons follow:

    1.可能的原因是你没有安装perl > yum install perl > yum install httpd-devel 2.在你apache安装目录下的bin下找到apxs,并用vi ...

  9. vi编辑时出现E325:ATTENTION

    我们用vi编辑文件时,系统会提示E325:ATTENTION. 这是由于在编辑该文件的时候异常退出了,因为vi在编辑文件时会创建一个交换文件swap file以保证文件的安全性. 但是每次打开文件时都 ...

  10. Golang之单元测试

    文件名必须以_test.go结尾 使用go test 执行单元测试 例 package main func add(a, b int) int { return a + b } func sub(a, ...