四、AutoFac 与 .NET Core 内置 IOC 的对比 —— 属性注入与模块化注册

前三篇我们把内置容器玩明白了,但有几个需求它就是办不到:属性注入、按名称注册、程序集一键扫描、AOP 拦截器。这些正是 Autofac 的主场。这篇讲清楚两件事:.NET 8 下怎么把 Autofac 无缝接进项目?以及什么场景才值得引入它——毕竟不是所有项目都需要。

一、内置容器为什么不支持属性注入

先说设计立场。微软官方对内置容器的定位是:只服务 DI 本身,刻意保持精简。它不支持:

  • 属性注入:依赖只能走构造函数;

  • 多构造函数自动选择:多个构造函数时无法智能挑选;

  • 按名称/Key 注册(.NET 8 加了 Keyed Services,但能力仍有限)、装饰器、拦截器。

官方的理由是:属性注入会隐藏依赖关系(不看构造函数签名不知道类依赖什么),并允许对象处于"半初始化"状态。所以内置容器有意不做——这不是能力不足,是设计取舍。

但现实中总有绕不开的场景:第三方类改不了构造函数、可选依赖、几十个 Service 想一键注册。这时就该 Autofac 出场了。

二、.NET 8 下接入 Autofac

引入两个包:Autofac 和 Autofac.Extensions.DependencyInjection,然后在通用主机上换掉服务提供者工厂:

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

var builder = Host.CreateApplicationBuilder(args);

// 换掉默认容器工厂并注册 Autofac 模块:此后所有服务都由 Autofac 解析
builder.ConfigureContainer(new AutofacServiceProviderFactory(), cb =>
{
    cb.RegisterType<EmailSender>().As<IMessageSender>().SingleInstance();
    cb.RegisterType<NotificationService>().PropertiesAutowired();
});

using var host = builder.Build();
host.Services.GetRequiredService<NotificationService>().Notify("xtyle");

 

builder.Services.AddTransient(...) 那套内置注册可以继续用——Autofac 会接管并兼容它们。也就是说可以渐进式迁移:公共库继续 IServiceCollection,应用层用 ContainerBuilder。

写法辨析:ASP.NET Core 的 WebApplicationBuilder 上用 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())(.Host 是 IHostBuilder 风格);控制台的 HostApplicationBuilder 没有 .Host 属性,用上面的 builder.ConfigureContainer(工厂, 配置委托) 扩展方法,效果相同。

三、Autofac 的增强能力

1. 属性注入(本次重点)

public class NotificationService
{
    public IMessageSender Sender { get; set; }   // 目标属性:公开可写
    public void Notify(string to) => Console.WriteLine(Sender.Send(to));
}

cb.RegisterType<NotificationService>().PropertiesAutowired();

 

PropertiesAutowired() 会自动给所有公开可写属性赋值。如果只想注入特定属性,用 OnActivated 回调更可控:

cb.Register(c =>
{
    var svc = new NotificationService();
    svc.Sender = c.Resolve<IMessageSender>();   // 手动挑属性
    return svc;
});

 

什么时候用属性注入?两个典型场景:依赖可选(缺了也能跑,比如可选的审计日志)、第三方类的构造函数改不了。业务代码里还是首选构造注入——这正是内置容器的立场。

2. 程序集批量扫描注册

cb.RegisterAssemblyTypes(typeof(OrderService).Assembly)
  .Where(t => t.Name.EndsWith("Service"))     // 按约定筛选
  .AsImplementedInterfaces()                  // 按实现的接口注册
  .InstancePerLifetimeScope();                // 等价于 Scoped

 

三行代码顶内置容器几百行 AddScoped,且新增 Service 类零注册成本——约定优于配置。

3. Module 模块化注册

注册逻辑按模块拆分,跨项目复用:

public class DataModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
        builder.RegisterAssemblyTypes(typeof(EfRepository<>).Assembly)
               .AsClosedTypesOf(typeof(IRepository<>));
    }
}

// 主程序里一行挂载
cb.RegisterModule<DataModule>();

 

4. 装饰器与拦截器

// 装饰器:给已有服务包一层,比如加缓存/日志,不动原实现
cb.RegisterType<CachedUserService>().As<IUserService>();
cb.RegisterDecorator<LoggingUserService, IUserService>();

// 拦截器(AOP):配合 Castle.DynamicProxy 实现方法级拦截
cb.RegisterType<LogInterceptor>();
cb.RegisterType<OrderService>().As<IOrderService>()
   .EnableInterfaceInterceptors()
   .InterceptedBy(typeof(LogInterceptor));

 

拦截器就是 .NET Core 里做 AOP 的经典方案,它和中间件、Filter 的关系与取舍,属于另一个大话题(对应我知识清单的 1.7),后面单独写系列展开。

四、两者怎么选:对比表

能力

内置容器

Autofac

构造函数注入

✅

✅

属性注入

❌(刻意不支持)

✅ PropertiesAutowired

三种生命周期

✅

✅(命名不同:InstancePerLifetimeScope = Scoped)

Keyed 按键注册

.NET 8+ ✅

✅(按名称/Key,历史更久)

程序集扫描

❌(需 Scrutor 或手写反射)

✅ 内置 RegisterAssemblyTypes

Module 模块化

❌

✅

装饰器 / 拦截器

❌

✅

多构造函数自动选择

❌

✅(UsingConstructor 或自动挑选"依赖最多满足的")

性能

极快(表达式树编译)

快

生态

框架原生、零依赖

第三方、功能全

选型建议:中小项目、没有 AOP 需求 → 内置容器足够,少一个依赖少一份维护成本;大型项目、需要批量约定注册/模块化/AOP → Autofac 值得引入。两者可以混用,迁移是渐进式的,不存在"二选一"的门槛。

五、完整示例

.NET 8/10 控制台程序,演示属性注入 + 批量扫描 + Module(需引入 Autofac、Autofac.Extensions.DependencyInjection 两个包):

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);
builder.ConfigureContainer(new AutofacServiceProviderFactory(), cb =>
{
    cb.RegisterType<EmailSender>().As<IMessageSender>().SingleInstance();
    cb.RegisterModule<BusinessModule>(); // 模块化注册:批量扫描 + 属性注入
});
using var host = builder.Build();

host.Services.GetRequiredService<NotificationService>().Notify("xtyle");

// ==== 类型定义 ====
public interface IMessageSender { string Send(string to); }
public class EmailSender : IMessageSender
{
    public string Send(string to) => $"[Email] -> {to}";
}

// 属性注入目标:注意没有构造函数参数
public class NotificationService
{
    public IMessageSender Sender { get; set; } = null!;
    public void Notify(string to) => Console.WriteLine(Sender.Send(to));
}

// 模块:程序集扫描 + 属性注入
public class BusinessModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(typeof(BusinessModule).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .PropertiesAutowired()
               .InstancePerLifetimeScope();
    }
}

 

输出:

[Email] -> xtyle

 

注意 NotificationService 的 Sender 属性是扫描 + PropertiesAutowired() 自动赋上的,全程没有任何一行代码"设置"它——这就是内置容器做不到的体验。

六、本篇面试问答

Q1:内置 IOC 容器和 Autofac 有什么区别? A:内置容器是微软刻意保持精简的实现,只支持构造函数注入和基础生命周期,优点是原生零依赖、表达式树编译解析极快;Autofac 提供属性注入、程序集批量扫描、Module 模块化、装饰器、基于 DynamicProxy 的拦截器、多构造函数选择等高级能力。两者可混用:通过 ConfigureContainer/UseServiceProviderFactory 让 Autofac 接管,IServiceCollection 的注册依然生效。

Q2:内置容器为什么不支持属性注入? A:官方的设计取舍——属性注入会隐藏类的真实依赖(依赖关系不再体现在构造函数签名上),并使对象可能处于半初始化状态。微软认为构造注入足以覆盖绝大多数场景,为保证容器精简与依赖显式性,有意不提供;需要时引入第三方容器。

Q3:什么场景值得引入 Autofac? A:三类信号:① 服务数量大,想用程序集扫描按约定批量注册;② 需要模块化拆分注册逻辑给多个团队/项目复用;③ 需要 AOP 拦截器或装饰器做统一日志、缓存、事务。只有属性注入一个需求时,也可以先用 ActivatorUtilities 或工厂注册变通,避免为单一功能引入整个第三方容器。


下一篇预告(系列收尾):BuildServiceProvider() 之后容器内部到底发生了什么?为什么它的解析速度接近手写 new?最后一篇拆解 ServiceProvider 的实现原理(表达式树 + CallSite),并把整个系列整理成一份面试高频题答案库。

posted @ 2026-11-30 22:39  Xtyle  阅读(2)  评论(0)    收藏  举报