ASP.NET MVC IOC依賴注入之Autofac系列(二)- WebForm當中應用


上一章主要介紹了Autofac在MVC當中的具體應用,本章將繼續簡單的介紹下Autofac在普通的WebForm當中的使用。

PS:目前本人還不知道WebForm頁面的構造函數要如何注入,以下在WebForm頁面將主要采用屬性注入的方式。

接下來我們正式進入主題,在上一章的基礎上我們再添加一個web項目TianYa.DotNetShare.WebDemo,首先看我們的解決方案

本demo的web項目為ASP.NET Web 應用程序(.NET Framework 4.5) 空Web窗體,需要引用以下幾個程序集:

1、TianYa.DotNetShare.Model 我們的實體層

2、TianYa.DotNetShare.Service 我們的服務層

3、TianYa.DotNetShare.Repository 我們的倉儲層,正常我們的web項目是不應該使用倉儲層的,此處我們引用是為了演示IOC依賴注入

4、Autofac 依賴注入基礎組件

5、Autofac.Web 依賴注入Web的輔助組件

其中Autofac和Autofac.Web可以從我們的NuGet上引用,依次點擊下載以下2個組件:

接着打開我們的Global.asax文件進行注入工作,Global需要實現IContainerProviderAccessor接口,如下所示:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using Autofac;
using Autofac.Integration.Web;
using TianYa.DotNetShare.Model;

namespace TianYa.DotNetShare.WebDemo
{
    public class Global : System.Web.HttpApplication, IContainerProviderAccessor
    {
        /// <summary>
        /// 依賴注入ContainerProvider
        /// </summary>
        static IContainerProvider _containerProvider;

        /// <summary>
        /// 實現IContainerProviderAccessor接口
        /// </summary>
        public IContainerProvider ContainerProvider
        {
            get
            {
                return _containerProvider;
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            AutofacRegister(); //Autofac依賴注入
        }

        /// <summary>
        /// Autofac依賴注入
        /// </summary>
        private void AutofacRegister()
        {
            var builder = new ContainerBuilder();

            //一次性注冊所有實現了IDependency接口的類
            Type baseType = typeof(IDependency);
            Assembly[] assemblies = 
                Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            builder.RegisterAssemblyTypes(assemblies)
                   .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
                   .AsSelf().AsImplementedInterfaces()
                   .PropertiesAutowired().InstancePerLifetimeScope();

            //設置依賴解析器
            _containerProvider = new ContainerProvider(builder.Build());
        }
    }
}

然后需要配置一下我們的Web.config,在configuration節點中添加system.webServer節點,如下所示:

<configuration>
  
  <!--Autofac依賴注入-->
  <system.webServer>
    <modules>
      <!-- This module handles disposal of the request lifetime scope. -->
      <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" preCondition="managedHandler" />
      <!-- This module injects properties on web forms. You could also use the UnsetPropertyInjectionModule or a custom module. -->
      <add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
</configuration>

最后來看下我們WebForm頁面

using System;

using TianYa.DotNetShare.Service;
using TianYa.DotNetShare.Repository;
using TianYa.DotNetShare.Repository.Impl;

namespace TianYa.DotNetShare.WebDemo
{
    public partial class Index : System.Web.UI.Page
    {
        /// <summary>
        /// 定義倉儲層學生實現類對象
        /// </summary>
        public StudentRepository StuRepositoryImpl { get; set; }

        /// <summary>
        /// 定義倉儲層學生抽象類對象
        /// </summary>
        public IStudentRepository StuRepository { get; set; }

        /// <summary>
        /// 通過屬性注入,訪問修飾符必須為public,否則會注入失敗
        /// </summary>
        public IStudentService StuService { get; set; }

        /// <summary>
        /// 頁面加載
        /// </summary>
        /// <param name="sender">引發事件的源</param>
        /// <param name="e">處理事件所需的參數</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            var stu1 = StuRepository.GetStuInfo("10000");
            var stu2 = StuService.GetStuInfo("10001");
            var stu3 = StuRepositoryImpl.GetStuInfo("10002");
            string msg = $"學號:10000,姓名:{stu1.Name},性別:{stu1.Sex},年齡:{stu1.Age}<br />";
            msg += $"學號:10001,姓名:{stu2.Name},性別:{stu2.Sex},年齡:{stu2.Age}<br />";
            msg += $"學號:10002,姓名:{stu3.Name},性別:{stu3.Sex},年齡:{stu3.Age}";

            Response.Write(msg);
        }
    }
}

至此,完成處理,接下來就是見證奇跡的時刻了,我們訪問一下 /index.aspx,看看是否能返回學生信息

可以發現,返回了學生的信息,說明我們注入成功了。

至此,我們的ASP.NET MVC IOC依賴注入之Autofac系列就全部介紹完了,如果你覺得這篇文章對你有所幫助請記得點贊哦,謝謝!!!

demo源碼:

鏈接:https://pan.baidu.com/s/1jUbf1pk2-bSybf9OfUh8Tw 
提取碼:24ki

 

參考博文:https://www.cnblogs.com/fei686868/p/11001873.html

版權聲明:如有雷同純屬巧合,如有侵權請及時聯系本人修改,謝謝!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM