You need to enable JavaScript to run this app. Autofac替代MEF按指定目录路径获取服务列表的实现方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Autofac替代MEF按指定目录路径获取服务列表的实现方案咨询

Autofac替换MEF实现目录扫描批量注册服务方案(VB.NET)

前置操作

  • 移除所有System.ComponentModel.Composition相关的库引用
  • 安装NuGet包:Autofac 5.2.0版本

实现逻辑对应说明

原有MEF逻辑和Autofac实现的对应关系:

  • 目录程序集加载:DirectoryCatalog → Autofac程序集扫描+RegisterAssemblyTypes批量注册
  • 部件组合:CompositionContainer.ComposeParts → 容器构建后直接解析接口集合
  • 批量获取服务:[ImportMany]特性 → 解析IEnumerable<IServiceProvider>接口集合

代码实现

引用命名空间

Imports Autofac
Imports System.IO
Imports System.Threading.Tasks

业务代码替换

Protected Property Services As List(Of IServiceProvider)

Public Sub StartServices(applicationDirectory As String)
    Me.applicationDirectory = applicationDirectory
    
    ' 初始化Autofac容器构建器
    Dim builder As New ContainerBuilder()
    
    ' 加载指定目录下所有dll程序集,批量注册IServiceProvider实现类
    Dim dllFiles = Directory.GetFiles(applicationDirectory, "*.dll", SearchOption.TopDirectoryOnly)
    For Each dllPath In dllFiles
        Try
            Dim targetAssembly = System.Reflection.Assembly.LoadFrom(dllPath)
            ' 注册所有实现IServiceProvider的类型到容器
            builder.RegisterAssemblyTypes(targetAssembly) _
                   .Where(Function(type) GetType(Team.Services.IServiceProvider).IsAssignableFrom(type)) _
                   .As(Of Team.Services.IServiceProvider)() _
                   ' 如需和MEF默认单例行为一致,替换为.SingleInstance()
                   .InstancePerDependency()
        Catch
            ' 跳过非合法.NET程序集的dll文件
            Continue For
        End Try
    Next
    
    ' 构建IoC容器
    Using container As IContainer = builder.Build()
        ' 解析所有已注册的IServiceProvider实例
        Services = container.Resolve(Of IEnumerable(Of Team.Services.IServiceProvider))().ToList()
        
        ' 原有并行启动逻辑不变
        If Services IsNot Nothing Then
            Parallel.ForEach(Services, Sub(service) service.StartService())
        End If
    End Using
End Sub

注意事项

  • 如需扫描子目录下的程序集,将SearchOption.TopDirectoryOnly修改为SearchOption.AllDirectories即可
  • 服务生命周期可根据业务调整:InstancePerDependency是每次解析创建新实例,SingleInstance是全局单例
  • 原MEF的<ImportMany>等特性可完全删除,不需要再保留任何MEF相关标记
  • 若服务存在构造函数依赖,只需将依赖的类型也注册到Autofac容器中,即可自动完成依赖注入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 23:24:02