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

C#使用Autofac时如何动态调用已实例化类的GetAll方法

解决方案

核心思路是利用Autofac容器自带的按类型解析实例能力,直接从生命周期作用域中获取对应接口的已注册实例,无需硬编码注入的具体实例,也不需要手动通过Activator创建对象。

改造步骤

1. 调整构造函数依赖注入

将原来注入的多个具体IxxxRecoverAndPersists接口替换为Autofac的ILifetimeScope,后续新增实现类无需修改构造函数:

private readonly ILifetimeScope _lifetimeScope;
private readonly IMapper _mapper;

public ChangeLogService(ILifetimeScope lifetimeScope, IMapper mapper)
{
    _lifetimeScope = lifetimeScope;
    _mapper = mapper;
}

2. 动态解析实例并调用方法

在获取到匹配的接口类型recoverAndPersistsType后,直接通过ILifetimeScope解析出对应实例,再调用GetAll方法即可:

var method = recoverAndPersistsType.GetMethod("GetAll");
// 动态解析已注册的实例
if (_lifetimeScope.TryResolve(recoverAndPersistsType, out var instance))
{
    var result = method.Invoke(instance, null);
    // 后续处理result逻辑
}

优化建议

可以给所有IxxxRecoverAndPersists接口提取公共基接口,避免反射调用方法,提升性能和可维护性:

// 定义公共基接口
public interface IRecoverAndPersists
{
    IEnumerable<object> GetAll();
}

// 原有子接口继承公共基接口
public interface IRewardTypeRecoverAndPersists : IRecoverAndPersists {}
public interface IChangeLogRecoverAndPersists : IRecoverAndPersists {}

优化后无需反射获取方法,直接调用即可:

if (_lifetimeScope.TryResolve(recoverAndPersistsType, out var objInstance) 
    && objInstance is IRecoverAndPersists instance)
{
    var result = instance.GetAll();
}

注意事项

  • 所有IxxxRecoverAndPersists接口需要提前在Autofac容器中完成实现类的注册
  • 可以根据业务需求调整GetAll方法的返回值类型,比如改成泛型返回适配不同业务场景

内容的提问来源于stack exchange,提问作者Morelli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:36:02