如果您想在使用WebAPI的ASP.NET中使用DI,则可以考虑使用Unity。
Unity是为现有的传统ASP.NET应用程序添加DI的最佳库。使用它,您甚至可以将DI添加到任何内容中,包括WebForms。
软件包:
<package id="Microsoft.AspNet.WebFormsDependencyInjection.Unity" version="1.0.0" targetFramework="net472" />
<package id="Unity" version="5.2.0" targetFramework="net472" />
<package id="Unity.Abstractions" version="3.3.0" targetFramework="net472" />
<package id="Unity.Container" version="5.8.6" targetFramework="net472" />
<package id="Unity.WebAPI" version="5.3.0" targetFramework="net472" />
Global.ascx:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
UnityConfigWebForms.RegisterComponents(this, AppConfig.WebAppSettings._authType);
UnityConfigWebAPI.RegisterComponents(AppConfig.WebAppSettings._authType);
...existing code...
示例类:
public static class UnityConfigWebAPI
{
public static void RegisterComponents(WebAppSettings.AuthenticationTypes authenticationType)
{
var container = new UnityContainer();
container.RegisterType<IWesTest, WesTest>(new Unity.Injection.InjectionConstructor("hi wesley, webapi"));
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
示例 WebAPI 类:
[Authorize]
public class TagController : ApiController
{
private AppStart.IWesTest _auth;
public TagController(AppStart.IWesTest auth)
{
this._auth = auth;
}
ConfigureServices(IServiceCollection services)
方法仅适用于 ASP.NET Core,为何在 ASP.NET Web API 中需要它? - Win