ASP.NET Core 3.1系列(28)——ASP.NET Core中使用Autofac替换内置IoC容器
创始人
2024-05-12 09:22:46
0

1、前言

前面的博客主要介绍了一些Autofac的使用方法,示例代码都是基于控制台程序。本文就来介绍一下如何在ASP.NET Core中使用Autofac代替内置的IoC容器。

2、创建接口和类

这里搭建了一个简易的项目,如下图所示:

在这里插入图片描述
Service层代码如下:

namespace App.Service.Contract
{public interface ICatService{string Get();}
}
namespace App.Service.Contract
{public interface IDogService{string Get();}
}
using App.Service.Contract;namespace App.Service
{public class CatService : ICatService{public string Get(){return "This is cat";}}
}
using App.Service.Contract;namespace App.Service
{public class DogService : IDogService{public string Get(){return "This is dog";}}
}

3、Autofac代替内置IoC容器

3.1、引入Autofac组件

新建一个Web API工程,使用NuGet引入如下组件:

Autofac
Autofac.Extensions.DependencyInjection

在这里插入图片描述

3.2、修改Program.cs

如果要使用Autofac代替内置的IoC容器,首先要对Program.cs进行修改,代码如下:

using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;namespace App
{public class Program{public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory())  // Autofac代替内置IoC容器.ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup();});}
}

上面加了一句UseServiceProviderFactory(new AutofacServiceProviderFactory()),该方法可以重写用于创建服务提供程序的工厂,也就是说现在已经将其替换为Autofac对应的工厂了。

3.3、修改Startup.cs

Startup.cs文件中,我们可以添加一个ConfigureContainer方法代替原有的ConfigureServices方法,代码如下:

using App.Service;
using App.Service.Contract;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;namespace App
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();}// Autofac注册接口和类public void ConfigureContainer(ContainerBuilder builder){builder.RegisterType().As().InstancePerLifetimeScope();builder.RegisterType().As().InstancePerLifetimeScope();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}
}

3.4、注入接口

创建一个控制器AnimalController,在构造函数中注入接口即可,代码如下:

using App.Service.Contract;
using Microsoft.AspNetCore.Mvc;namespace App.Controllers
{[Route("api/[controller]/[action]")][ApiController]public class AnimalController : ControllerBase{protected readonly ICatService _cat;protected readonly IDogService _dog;public AnimalController(ICatService cat, IDogService dog){_cat = cat;_dog = dog;}[HttpGet]public ActionResult Get(){return _cat.Get() + "\n" + _dog.Get();}}
}

运行结果如下所示:

This is cat
This is dog

3.5、单独配置Autofac模块

之前的博客介绍过,实际业务中一般会对Autofac进行单独配置。新建一个类AutofacModule,代码如下:

using App.Service;
using App.Service.Contract;
using Autofac;namespace App
{public class AutofacModule : Module{protected override void Load(ContainerBuilder builder){builder.RegisterType().As().InstancePerLifetimeScope();builder.RegisterType().As().InstancePerLifetimeScope();}}
}

修改一下Startup.cs文件,代码如下:

using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;namespace App
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();}// Autofac注册接口和类public void ConfigureContainer(ContainerBuilder builder){builder.RegisterModule(new AutofacModule());}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}
}

运行程序,输出结果也是一样的:

This is cat
This is dog

4、结语

本文主要介绍了在ASP.NET Core中使用Autofac代替内置IoC容器的方法。相较于内置的IoC容器,Autofac功能更加丰富、使用更加灵活,在实际业务中合理使用Autofac可以极大提升开发效率,同时也更加便于项目后期的维护。

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...