[译]Use Dependency Injection In WebForms Application

时间:2021-10-16 08:40:35

怎么在已用的WebForm应用中使用DI

假设有一个电影网站,有个页面会列出最近热门的电影。这个项目中使用了仓储模式来获取数据。

public partial class Default : System.Web.UI.Page
{
private IPopularMovie movieMgr = new MovieManager(new XmlMovieRepository()); public async Task<SelectResult> movieList_GetData()
{
var movies = await movieMgr.GetPopularMoviesAsync();
return new SelectResult(movies.Count(), movies);
}
}

按照下面的4个步骤,可以在default.aspx.cs中使用DI。

1. 将项目指定为.NET Framework 4.7.2.

[译]Use Dependency Injection In WebForms Application

同时还需要修改web.config中的httpRuntime section的targetFramework。

[译]Use Dependency Injection In WebForms Application

2. 安装AspNet.WebFormsDependencyInjection.Unity NuGet package

[译]Use Dependency Injection In WebForms Application

3. 在Global.asax中注册类型

using System;
using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using PopularMovies.Bizlogic;
using PopularMovies.Repository;
using Unity; namespace PopularMovies
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
var container = this.AddUnity(); container.RegisterType<IPopularMovie, MovieManager>();
container.RegisterType<IMovieRepository, XmlMovieRepository>();
}
}
}

4. 修改 Default.aspx.cs

public partial class Default : System.Web.UI.Page
{
private IPopularMovie movieMgr;
public Default(IPopularMovie movieManager)
{
movieMgr = movieManager;
} public async Task<SelectResult> movieList_GetData()
{
var movies = await movieMgr.GetPopularMoviesAsync();
return new SelectResult(movies.Count(), movies);
}
}

可以在哪些地方使用DI?

  • Pages and controls
    • WebForms page
    • User control
    • Custom control
  • IHttpHandler and IHttpHandlerFactory
  • IHttpModule
  • Providers
    • BuildProvider
    • ResourceProviderFactory
    • Health monitoring provider
    • Any ProviderBase based provider created by System.Web.Configuration.ProvidersHelper.InstantiateProvider. e.g. custom sessionstate provider