惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
腾讯CDC
J
Java Code Geeks
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
博客园 - Franky
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
云风的 BLOG
云风的 BLOG
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
雷峰网
雷峰网
B
Blog RSS Feed
博客园_首页
量子位
F
Fortinet All Blogs
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog

博客园 - 咖啡色

拆解 Claude Code 源码:如何用软件工程思维约束 AI? 为什么要在.Net Core中使用MediatR library? Let’s Encrypt 项目计划自动化地提供免费的 CA 证书 论C#逼格手册 这些.NET开源项目你知道吗?让.NET开源来得更加猛烈些吧!(第二辑) Entity Framework where语句起作用的真正用法 ASP.NET Page_Load执行两次 [转]SqlServer 表分区详细介绍 HttpPostedFileBase always null when upload file by asp.net mvc4 mobile 一步步构建大型网站架构 TCP/IP网络协议的通俗理解,socket,http,soap。 精妙Sql语句备忘 解决.net绘制的 WinForm 在 windows7下变形的方法 关于 ASP.net + JQuery + JQGrid + JSON.net 的简单应用(一) Entity Framework 连接 mysql 5.0出现的问题及解决方案 VSTO开发中VS2010和Office 2003的问题及解决方案 如何使用缓存提高程序性能 如何用Javascript写一个Class? 程序员装逼指南(网上看到的,笑喷了……)
.NET:在ASPX、ASHX和MVC中使用IOC容器(菜鸟必看)
咖啡色 · 2013-05-03 · via 博客园 - 咖啡色

来源:http://www.cnblogs.com/happyframework/archive/2013/04/29/3050353.html

前言

程序开发的一个良好原则就是:“将使用和创建分开”。5年前有多少人采用这种风格呢?几乎没有。在IOC流行甚至泛滥的今天,还有一些团队没有使用IOC容器,有些是由于历史原因,有些是由于团队的文化。没有采用IOC的团队,找个机会拥抱一下吧。

我一直在用IOC容器,在此介绍一下如何将IOC集成到WebForm和WebMvc的应用系统中。

自动注入到ASPX和ASHX

框架支持

复制代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Happy.Web
 8 {
 9     public interface IWantAutoDependInjection
10     {
11     }
12 }

复制代码

复制代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Happy.Web
 8 {
 9     [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
10     public sealed class DependToAttribute : Attribute
11     {
12         public Type DependToType { get; set; }
13 
14         public string Key { get; set; }
15     }
16 }

复制代码

复制代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using System.Web;
 8 
 9 using Microsoft.Practices.ServiceLocation;
10 
11 using Happy.ExtensionMethods.Reflection;
12 
13 namespace Happy.Web
14 {
15     public class DependInjectionModule : IHttpModule
16     {
17         public void Init(HttpApplication context)
18         {
19             context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
20         }
21 
22         private void OnPreRequestHandlerExecute(object sender, EventArgs e)
23         {
24             if (!(HttpContext.Current.CurrentHandler is IWantAutoDependInjection))
25             {
26                 return;
27             }
28 
29             var properties = HttpContext.Current.CurrentHandler.GetType().GetProperties();
30 
31             foreach (var property in properties)
32             {
33                 var dependToAttribute = property.GetAttribute<DependToAttribute>(false);
34 
35                 if (dependToAttribute == null)
36                 {
37                     continue;
38                 }
39 
40                 var dependType = dependToAttribute.DependToType ?? property.PropertyType;
41 
42                 var value = ServiceLocator.Current.GetInstance(dependType, dependToAttribute.Key ?? string.Empty);
43 
44                 property.SetValue(HttpContext.Current.Handler, value);
45             }
46         }
47 
48         public void Dispose()
49         {
50         }
51     }
52 }

复制代码

代码示例

复制代码

 1 <configuration>
 2   <system.web>
 3     <compilation debug="true" targetFramework="4.5" />
 4     <httpRuntime targetFramework="4.5" />
 5   </system.web>
 6 
 7   <system.webServer>
 8     <modules>
 9       <add name="DependInjectionModule" type="Happy.Web.DependInjectionModule"/>
10     </modules>
11   </system.webServer>
12 
13 </configuration>

复制代码

复制代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 using Happy.Web;
 9 
10 namespace WebStudy
11 {
12     public partial class Test : System.Web.UI.Page, IWantAutoDependInjection
13     {
14         [DependTo]
15         public ApplicationService ApplicationService { get; set; }
16 
17         protected void Page_Load(object sender, EventArgs e)
18         {
19             this.Response.Write(this.ApplicationService.GetMessage());
20         }
21     }
22 
23     public sealed class ApplicationService
24     {
25         public string GetMessage()
26         {
27             return "段光伟";
28         }
29     }
30 }

复制代码

运行结果

 

自动注入到MVC

框架支持(最新版本)

复制代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using System.Web.Routing;
 8 using System.Web.Mvc;
 9 
10 using Microsoft.Practices.ServiceLocation;
11 
12 using Happy.DesignByContract;
13 
14 namespace Happy.Web.Mvc
15 {
16     public sealed class ServiceLocationDependencyResolver : IDependencyResolver
17     {
18         private readonly IServiceLocator _serviceLocator;
19 
20         public ServiceLocationDependencyResolver(IServiceLocator serviceLocator)
21         {
22             Check.RequireNotNull(serviceLocator, "serviceLocator");
23 
24             _serviceLocator = serviceLocator;
25         }
26 
27         public object GetService(Type serviceType)
28         {
29             Check.RequireNotNull(serviceType, "serviceType");
30 
31             try
32             {
33                 return _serviceLocator.GetInstance(serviceType);
34             }
35             catch
36             {
37                 return null;
38             }
39         }
40 
41         public IEnumerable<object> GetServices(Type serviceType)
42         {
43             Check.RequireNotNull(serviceType, "serviceType");
44 
45             try
46             {
47                 return _serviceLocator.GetAllInstances(serviceType);
48             }
49             catch
50             {
51                 return new List<object>();
52             }
53         }
54     }
55 }

复制代码

代码示例

此处省略代码示例,有兴趣的朋友请留言交流。

备注

想象一下,开发人员只需要定义和声明,不需要手工组装(new)会有多爽。IOC容器的配置最好根据约定自动配置。