Autofac的几种方式

发布时间 2023-12-06 15:23:33作者: ProZkb

.net下优秀的IOC容器框架Autofac的使用方法,实例解析 - 知乎 (zhihu.com)

 

UseServiceProviderFactory(使用服务提供商) 是在 ASP.NET Core 中用来替换默认的依赖注入容器工厂的方法
通过使用不同的容器工厂,可以使用第三方的依赖注入容器(如 Autofac、Ninject 等),以替代默认的 ASP.NET Core 依赖注入容器。

具体来说,UseServiceProviderFactory 方法接受一个实现了 IServiceProviderFactory<TContainerBuilder> 接口的容器工厂实例作为参数。
该接口定义了一个 CreateBuilder 方法,用于创建容器构建器,并在其上进行配置。
CreateBuilder 方法将在应用程序启动时被调用,用于创建容器构建器,以及在其中进行服务的注册和配置。

1.Main方法中代码

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    //使用AutoFac 方式
    builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();    
    //Swagger UI
    builder.Services.AddSwaggerGen();
//使用.NET Generic Host 中的 ConfigureContainer 方法来配置依赖注入容器。 //在这里,使用了 Autofac 容器,因此使用的是 ContainerBuilder 类型。 //具体来说,.Host.ConfigureContainer<ContainerBuilder>(x => { ... }) 这段代码表示在 Generic Host 的构建过程中,对依赖注入容器进行配置。 //其中的 x 是一个 ContainerBuilder 类型的参数,用于注册依赖项 //在代码中,通过 RegisterModule 方法注册了一个名为 TestCoreModule 的模块,这个模块实现了 Autofac 的 Module 类 //在 TestCoreModule 中可以包含一些特定的服务注册逻辑,以便在整个应用程序中使用 builder.Host.ConfigureContainer<ContainerBuilder>(x => { //TestCoreModule 是一个实现了AutoFac.Module 的一个类Module x.RegisterModule(new TestCoreModule()); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); }

2.TesCoreModule的实现

using Autofac;
namespace AutofacServiceDemo
{
    public class TestCoreModule: Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<SonCaseService>().As<ICaseService>().InstancePerLifetimeScope();
        }
    }
}

3:接口和派生类(业务层面)

namespace AutofacServiceDemo
{
    public interface ICaseService
    {
        string Ret();
    }

    public class SonCaseService : ICaseService
    {
        public string Ret()
        {
            return "我是实现类";
        }
    }
}

4:控制器层面

using Microsoft.AspNetCore.Mvc;

namespace AutofacServiceDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TestController : Controller
    {

        private readonly ICaseService _caseService;

        public TestController(ICaseService caseService)
        {
            _caseService = caseService;
        }

        [HttpPost()]
        public IActionResult Index(string id,string name)
        {
            var ret = _caseService.Ret();
            return Ok();
        }
    }
}