ASP.NET WebApi + Autofac 實現依賴注入

潇沫明月發表於2024-08-29

方法1
1.1、專案情況
框架:.NET Framework 4.5
Autofac 3.5.0
Autofac.WebApi2 4.3.0

1.2、定義介面與對應實現
// 介面1
public interface IBaseUserService
{
List<BaseUser> GetBaseUserList();
}
// 介面2
public interface IBaseCloseLoopService
{
List<BaseCloseLoop> GetBaseCloseLoopList();
}

// 實現1
public class BaseUserService : IBaseUserService
{
public List<BaseUser> GetBaseUserList()
{
BaseUserDao dao = new BaseUserDao();
return dao.GetModelList();
}

}
// 實現2
public class BaseCloseLoopService : IBaseCloseLoopService
{
public List<BaseCloseLoop> GetBaseCloseLoopList()
{
BaseCloseLoopDao dao = new BaseCloseLoopDao();
return dao.GetModelList();
}
}
1.3、新增Autofac配置類
public class AutofacConfig
{
public static Autofac.IContainer _container;

public static void Configure()
{
var builder = new ContainerBuilder();
var config = System.Web.Http.GlobalConfiguration.Configuration;

// OPTIONAL: Register the Autofac filter provider.
//builder.RegisterWebApiFilterProvider(config);
// OPTIONAL: Register the Autofac model binder provider.
//builder.RegisterWebApiModelBinderProvider();

// 指定介面的實現類
builder.RegisterType<BaseUserService>().As<IBaseUserService>().AsImplementedInterfaces();
builder.RegisterType<BaseCloseLoopService>().As<IBaseCloseLoopService>().AsImplementedInterfaces();
// 一次性註冊所有【實現了baseTyp介面的類】;不建議,無法指定介面實現類
//Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
//List<Type> baseTypeList = new List<Type>()
//{
// typeof(IBaseUserService),
// typeof(IBaseCloseLoopService)
//};
//builder.RegisterAssemblyTypes(assemblies).Where(type => baseTypeList.Any(t => t.IsAssignableFrom(type)) && !type.IsAbstract).AsSelf().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();

// 註冊 Web API Controllers
builder.RegisterApiControllers(System.Reflection.Assembly.GetExecutingAssembly());
_container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(_container);
}
}



// ================================ 分割線 ==========================================

// 以下為ASP.NET MVC的Autofac配置,注意引用的DLL有所不同,此處不詳述
public class AutofacConfig
{
public static Autofac.IContainer _container;
public static void Register()
{
var builder = new ContainerBuilder();
builder.RegisterType<BaseCloseLoopService>().As<IBaseCloseLoopService>();
builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
_container = builder.Build();
System.Web.Mvc.DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(_container));
}
}
1.4、在Global.asax引用配置
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

//autofac ioc配置
AutofacConfig.Configure();
}
}
1.5、ApiController使用
public class CloseLoopController : ApiController
{
// 需要注入的介面
private readonly IBaseUserService _baseUserService;
private readonly IBaseCloseLoopService _baseCloseLoopService;
/// <summary>
/// 建構函式注入
/// </summary>
/// <param name="baseUserService"></param>
/// <param name="baseCloseLoopService"></param>
public CloseLoopController(IBaseUserService baseUserService, IBaseCloseLoopService baseCloseLoopService)
{
_baseUserService = baseUserService;
_baseCloseLoopService = baseCloseLoopService;
}


[HttpGet]
public string GetBaseUser([FromBody] object json)
{
// 直接呼叫方法即可
var result = _baseUserService.GetBaseUserList();
return JsonConvert.SerializeObject(result);
}

[HttpGet]
public string GetBaseCloseLoop([FromBody] object json)
{
var result = _baseCloseLoopService.GetBaseCloseLoopList();
return JsonConvert.SerializeObject(result);
}

}
方法2
2.1、安裝包
前面方法1的前提下,再Nuget安裝 Autofac.Configuration

2.2、web.config配置autofac
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration" />
</configSections>
<autofac>
<components>
<component type="Autofac.Test.Service.BaseUserService, Autofac.Test.Service" service="Autofac.Test.Contracts.IBaseUserService, Autofac.Test.Contracts" />
<component type="Autofac.Test.Service.BaseCloseLoopService, Autofac.Test.Service" service="Autofac.Test.Contracts.IBaseCloseLoopService, Autofac.Test.Contracts" />
</components>
</autofac>
</configuration>
2.3、新建autofac幫助類,讀取配置生成例項
using Autofac;
using Autofac.Configuration;

public class IOCHelper
{
public static TInterface GetObject<TInterface>(string sectionName)
{
Autofac.ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule(new Autofac.Configuration.ConfigurationSettingsReader(sectionName));
IContainer container = builder.Build();
TInterface dal = container.Resolve<TInterface>();
return dal;
}
}
2.4、呼叫
private IBaseUserService userService = IOCHelper.GetObject<IBaseUserService>("autofac");

相關文章