ASP.NET Core 3.1系列(28)——ASP.NET Core中使用Autofac替换内置IoC容器

1、前言

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

2、创建接口和类

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

ASP.NET Core 3.1系列(28)——ASP.NET Core中使用Autofac替换内置IoC容器_第1张图片
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

ASP.NET Core 3.1系列(28)——ASP.NET Core中使用Autofac替换内置IoC容器_第2张图片

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<Startup>();
                });
    }
}

上面加了一句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<CatService>().As<ICatService>().InstancePerLifetimeScope();
            builder.RegisterType<DogService>().As<IDogService>().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<string> 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<CatService>().As<ICatService>().InstancePerLifetimeScope();
            builder.RegisterType<DogService>().As<IDogService>().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可以极大提升开发效率,同时也更加便于项目后期的维护。

你可能感兴趣的:(ASP.NET,Core,C#,ASP.NET,Core)