首页 > 编程语言 >ASP.NET WebApi + Autofac 实现依赖注入

ASP.NET WebApi + Autofac 实现依赖注入

时间:2024-08-29 10:48:54浏览次数:6  
标签:WebApi Autofac ASP container builder class new public

方法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");

标签:WebApi,Autofac,ASP,container,builder,class,new,public
From: https://www.cnblogs.com/kissy/p/18386160

相关文章

  • ASP.NET Core 入门教程三 结合 EFCore 和 SQLite
    ASP.NETCore是一个开源的Web框架,它允许开发者轻松地构建现代、高性能的Web应用程序。EntityFrameworkCore(EFCore)是一个轻量级、可扩展的ORM(对象关系映射)框架,它支持多种数据库。SQLite是一个轻量级的嵌入式数据库,适用于小型应用程序。在本篇文章中,我们将学习如何......
  • @aspectJ机制剖析
    @aspectJ机制剖析@aspectj通过修改字节码文件来实现目标方法的增强。org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitializationorg.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitializationA......
  • 【音视频通话】使用asp.net core 8+vue3 实现高效音视频通话
    引言在三年前,写智能小车的时候,当时小车上有一个摄像头需要采集,实现推拉流的操作,技术选型当时第一版用的是nginx的rtmp的推拉流,服务器的配置环境是centos,2H4G3M的一个配置,nginx的rtmp的延迟是20秒,超慢,后来研究了SRS以及ZLMediaKit这两个开源的推拉流服务器,没记错的话,两个......
  • Asp.Net Core中Typed HttpClient高级用法
    另一个常见的需求是根据不同的服务接口创建不同的HttpClient实例。为了实现这一点,ASP.NETCore提供了TypedHttpClient的支持。下面是使用TypedHttpClient的示例代码:publicinterfaceIExampleService{Task<string>GetData();}publicclassExampleService:IExampl......
  • 界面控件Telerik UI for ASP.NET Core 2024 Q2亮点 - AI与UI的融合
    TelerikUIforASP.NETCore是用于跨平台响应式Web和云开发的最完整的UI工具集,拥有超过60个由KendoUI支持的ASP.NET核心组件。它的响应式和自适应的HTML5网格,提供从过滤、排序数据到分页和分层数据分组等100多项高级功能。本文将介绍界面组件TelerikUIforASP.NETCore在今年......
  • 驾驭ASP.NET MVC:C# Web开发的精粹
    标题:驾驭ASP.NETMVC:C#Web开发的精粹摘要ASP.NETMVC是微软提供的一个用于构建动态网站的服务器端框架,它遵循模型-视图-控制器(MVC)设计模式,以实现代码的高内聚低耦合。本文将深入探讨如何在C#中使用ASP.NETMVC框架进行Web应用程序开发,包括项目结构、路由、控制器、视图和......
  • Spring源码第十七讲 @Aspect 到 Advisor
    先做一些准备工作publicclassA017{publicstaticvoidmain(String[]args){GenericApplicationContextcontext=newGenericApplicationContext();context.registerBean("aspect1",Aspect1.class);context.registerBean("con......
  • ASP.NET8 中使用 AutoMapper 配置
    ASP.NET8中使用AutoMapper配置菜鸟新人学习.NET记录,找到了个类似Springboot框架中的Mapstruct的工具,就是配置资料不是很多,踩了蛮多坑的。假设现在有一个USER类,我想将它转换成USERVO把其中的pwd字段給隐藏掉,通过AutoMapper可以不用每个字段赋值创建对象这样子,直接上......
  • ASP.Net8 中使用 JWT 鉴权的异常处理
    .Net8中使用JWT鉴权的异常处理自己搭了个学习Demo想用JWT給后端做鉴权,结果一直报一些奇奇怪怪的异常,最主要是和写业务代码不一样,因为用了官方提供的包很难排查出问题所在,这次有点像以前学Spring的时候,也是一点一点摸着石头过河,最后还是同事帮忙看出来问题在哪的。问题1:I......
  • .NET Core 处理 WebAPI JSON 返回烦人的null为空
    前言   项目开发中不管是前台还是后台都会遇到烦人的null,数据库表中字段允许空值,则代码实体类中对应的字段类型为可空类型Nullable<>,如int?,DateTime?,null值字段序列化返回的值都为null,前台对应字段赋值需要做null值判断,怎么才能全局把null替换为空。    本文分享Web......