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

32 篇文章 42 订阅

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<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可以极大提升开发效率,同时也更加便于项目后期的维护。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值