You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Autofac中注册泛型适配器以实现指定泛型接口的适配

Autofac泛型适配器注册实现方案

你需要的适配功能可以通过Autofac原生的泛型注册能力实现,不需要依赖第三方扩展,具体实现逻辑如下:

1. 适配类结构约定

首先你的适配器类需要构造注入被适配的泛型服务,示例结构如下:

// 被适配的服务泛型接口
public interface IProcessor<T>
{
    void Process(T data);
}

// 适配器对外暴露的泛型接口
public interface IProcessorInvoker<T>
{
    void Run(T data);
}

// 适配器实现,完成IProcessor<T>到IProcessorInvoker<T>的适配
public class ProcessorInvoker<T> : IProcessorInvoker<T>
{
    private readonly IProcessor<T> _adapted;

    // 构造函数注入对应泛型参数的被适配服务
    public ProcessorInvoker(IProcessor<T> adapted)
    {
        _adapted = adapted;
    }

    public void Run(T data)
    {
        // 自定义适配逻辑,比如加日志、参数校验后调用原始服务
        Console.WriteLine("执行适配前置逻辑");
        _adapted.Process(data);
        Console.WriteLine("执行适配后置逻辑");
    }
}

2. 原生注册方式

直接使用Autofac内置的RegisterGeneric方法注册泛型适配器即可,Autofac会自动为每个闭合泛型类型匹配对应的被适配服务实例:

var builder = new ContainerBuilder();

// 先注册所有业务实现的IProcessor<>闭合类型服务
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
    .AsClosedTypesOf(typeof(IProcessor<>));

// 注册泛型适配器,绑定到IProcessorInvoker<>服务接口
builder.RegisterGeneric(typeof(ProcessorInvoker<>))
    .As(typeof(IProcessorInvoker<>));

// 构建容器后即可直接解析对应泛型参数的适配器
using var container = builder.Build();
var intInvoker = container.Resolve<IProcessorInvoker<int>>();
intInvoker.Run(100);

3. 自定义扩展方法(匹配你示例的调用方式)

如果你需要封装成你示例中提到的RegisterGenericAdapter调用形式,可以自定义Autofac扩展方法:

public static class GenericAdapterRegistrationExtensions
{
    public static IRegistrationBuilder<object, ReflectionActivatorData, DynamicRegistrationStyle> 
        RegisterGenericAdapter(
        this ContainerBuilder builder,
        Type adapterImplType,
        Type adaptedServiceType,
        Type adapterServiceType)
    {
        // 泛型参数校验
        if (!adapterImplType.IsGenericTypeDefinition)
            throw new ArgumentException("适配器实现必须为开放泛型类型", nameof(adapterImplType));
        if (!adaptedServiceType.IsGenericTypeDefinition)
            throw new ArgumentException("被适配服务必须为开放泛型类型", nameof(adaptedServiceType));
        if (!adapterServiceType.IsGenericTypeDefinition)
            throw new ArgumentException("适配器服务必须为开放泛型类型", nameof(adapterServiceType));

        return builder.RegisterGeneric(adapterImplType).As(adapterServiceType);
    }
}

封装完成后即可使用你示例中的写法注册:

builder.RegisterGenericAdapter(typeof(ProcessorInvoker<>), typeof(IProcessor<>), typeof(IProcessorInvoker<>));

内容的提问来源于stack exchange,提问作者Börg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:36:04