zoukankan      html  css  js  c++  java
  • 架构视角面面观之: WebPage能支持DI注入那该多好

      关于什么是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 运行即可看到结果!

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

  • 相关阅读:
    windows 10 上源码编译opengv | compile opengv on windows 10 from source
    ubuntu 16.04上源码编译libjpeg-turbo和使用教程 | compile and use libjpeg-turbo on ubuntu 16.04
    c 时间 学习
    cap文件的格式说明
    C#调用C++
    c/c++基础 const
    tomcat 简单安装配置说明
    言论
    近期任务
    解决mysql从windows迁移到centos出现乱码问题
  • 原文地址:https://www.cnblogs.com/netcasewqs/p/2547848.html
Copyright © 2011-2022 走看看