现在的位置: 首页 > 综合 > 正文

DI,DIP,IOC的演变历史

2011年02月15日 ⁄ 综合 ⁄ 共 1202字 ⁄ 字号 评论关闭

  关于什么是DI注入,很多人应该都很熟悉,如果不太熟悉,可以看看园友的一篇文章 DI,DIP,IOC的演变历史

     DI 注入常常用在Mvc的项目或者领域层和持久层,但是如果DI注入能够和WebPage完美的结合起来,那就更完美了,那么下面就开始了。

  1.          新建Web项目-WebPageWithDI
  2.          打开Nuget控制台 并键入install-package nlite.web 
  3.          在Web配置文件中加入如下代码:
    <httpHandlers>
          <add path="*.aspx" verb="*" type="NLite.Web.PageHandlerFactory, NLite.Web" />
    </httpHandlers>

     4.         写一个简单的计算器服务

   public interface ICalculateService
    {
        int Add(int a, int b);
        int Divide(int a, int b);
        int Multiply(int a, int b);
        int Sub(int a, int b);
    }

    public class CalculateService : ICalculateService
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Sub(int a, int b)
        {
            return a - b;
        }
        public int Multiply(int a, int b)
        {
            return a * b;
        }
        public int Divide(int a, int b)
        {
            return a / b;
        }
    }

     5.     注册刚才的组件到DI容器中

using NLite;
using NLite.Cfg;

void Application_Start(object sender, EventArgs e) { //创建一个配置对象 var cfg = new Configuration(); //进行确实配置(配置DI容器) cfg.Configure(); //注册CalculateService组件到容器中  ServiceRegistry.Register(f => f.Bind<ICalculateService>().To<CalculateService>().Transient()); }

  6. 新建一个Test页面,然后在Test.aspx.cs 中利用DI自动注入来使用刚刚注册的组件

using NLite;

     [Inject]
protected ICalculateService Service; protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.Write("3 + 2 = " + Service.Add(3, 2).ToString()); }

  7. F5 运行即可看到结果!

     如此简单,是否愿意尝试呢?

 

 

【上篇】
【下篇】

抱歉!评论已关闭.