依賴注入技術就是將一個物件注入到一個需要它的物件中,同時它也是控制反轉的一種實作,顯而易見,這樣可以實作物件之間的解耦并且更方便測驗和維護,依賴注入的原則早已經指出了,應用程式的高層模塊不依賴于低層模塊,而應該統一依賴于抽象或者介面,
在 .Net Framework 4.7.2 中引入了對依賴注入的支持,終于在 ASP.Net Web Forms 中可以使用依賴注入機制了,這篇文章將會討論如何在 ASP.Net Web Forms 中去使用,
創建 WebForm 專案
在 ASP.Net Web Forms 中使用依賴注入,一定要記得將專案框架設為 4.7.2 以上,要么右鍵專案在屬性面板上選擇 4.7.2 版本,
也可以直接在 web.config 做如下設定,
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
...
</system.web>
接下來就可以通過 Nuget 安裝 AspNet.WebFormsDependencyInjection.Unity 包,可以通過 Visual Studio 2019 的 NuGet package manager 可視化界面安裝 或者 通過 NuGet package manager 命令列工具輸入以下命令:
dotnet add package AspNet.WebFormsDependencyInjection.Unity
創建物體 和 介面
現在創建一個名為 Author 物體類 和 IAuthorRepository 介面,
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public interface IAuthorRepository
{
bool Create(Author author);
Author Read(int id);
List<Author> Read();
}
然后再用 AuthorRepository 類實作一下 IAuthorRepository 介面,代碼如下:
public class AuthorRepository : IAuthorRepository
{
public bool Create(Author author)
{
throw new System.NotImplementedException();
}
public Author Read(int id)
{
throw new System.NotImplementedException();
}
public List<Author> Read()
{
throw new System.NotImplementedException();
}
}
創建容器和型別注冊
現在我們創建 依賴注入容器,然后注入我們想要的型別,下面的代碼用于創建 Unity容器,
var container = this.AddUnity();
然后在 Application_Start 事件中進行物件的 依賴配置,如下代碼所示:
container.RegisterType<IAuthorRepository, AuthorRepository>();
對了,記的引入一下如下兩個命名空間,
-
AspNet.WebFormsDependencyInjection.Unity
-
Unity
下面是 Global 類的完整代碼,僅供參考,
using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using Unity;
namespace WebformsDIDemo
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
var container = this.AddUnity();
container.RegisterType<IAuthorRepository, AuthorRepository>();
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
WebForms 使用依賴注入
現在容器,物件依賴都配置好了,接下來怎么在 Page 中用呢? 可以參考下面的代碼,
public partial class _Default : Page
{
private IAuthorRepository _authorRepository;
public _Default(IAuthorRepository authorRepository)
{
_authorRepository = authorRepository;
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
上面的圖很明顯的顯示了,authorRepository 實體在運行時中已被成功注入,
在 .Net Framework 4.7.2 框架以上,終于將 依賴注入機制 帶入到了 ASP.Net Web Forms 中,需要明白的是,微軟自帶的Unity包是一個輕量級的依賴注入容器,可以在 頁面,控制元件,handler,module 上使用,在 ASP.Net Web Forms 中使用依賴注入可以輕松創建物件,然后在運行時獲取依賴,可讓你輕松構建靈活,松散的應用程式,
更多精彩,歡迎訂閱 ??????

譯文鏈接:https://www.infoworld.com/article/3397003/how-to-use-dependency-injection-in-aspnet-web-forms.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/270413.html
標籤:C#
