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

C#如何基于配置动态加载自定义程序集中的指定类型?

动态加载指定类型的C#实现方案

嘿,我来帮你搞定这个动态加载类型的需求!先从你给出的配置字符串说起,然后一步步给你落地的实现方案~

首先,你提到的配置字符串 "MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services" 是C#中类型的完全限定标识格式,它的含义是:

  • 逗号前的 MyOrg.MyApp.Services.Example:要加载的目标类型的完全限定名,也就是完整命名空间 + 类名;
  • 逗号后的 MyOrg.MyApp.Services:包含这个类型的程序集名称(就是你的类库编译后生成的.dll文件的名称,不带.dll后缀)。

接下来是具体的实现步骤和代码示例:

步骤1:准备类库(推荐定义接口约束)

为了让动态加载的类型更易使用,建议在你的模板类库中定义一个接口,让目标类型实现这个接口。这样后续调用时不需要大量反射,直接转成接口调用即可:

namespace MyOrg.MyApp.Services
{
    public interface IBusinessService
    {
        void Execute();
    }

    public class Example : IBusinessService
    {
        public void Execute()
        {
            Console.WriteLine("Example服务已执行!");
        }
    }
}

步骤2:主应用中解析配置并动态加载

在你的C#主应用中,按照以下流程实现动态加载:

  1. 解析配置字符串,拆分出类型名和程序集名;
  2. 加载目标程序集;
  3. 获取目标类型;
  4. 实例化类型并调用方法。

代码示例如下:

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        // 模拟从配置读取(实际项目中可以用IConfiguration读取appsettings.json等配置文件)
        string typeConfig = "MyOrg.MyApp.Services.Example, MyOrg.MyApp.Services";

        // 拆分配置字符串,注意去除前后空格
        var configParts = typeConfig.Split(',', StringSplitOptions.RemoveEmptyEntries);
        string typeFullName = configParts[0].Trim();
        string assemblyName = configParts[1].Trim();

        try
        {
            // 加载程序集(如果程序集不在默认搜索路径,可改用Assembly.LoadFrom指定路径)
            Assembly targetAssembly = Assembly.Load(assemblyName);

            // 获取目标类型
            Type targetType = targetAssembly.GetType(typeFullName);
            if (targetType == null)
            {
                throw new InvalidOperationException($"未在程序集 {assemblyName} 中找到类型 {typeFullName}");
            }

            // 实例化类型(如果类型有非默认构造函数,可传入对应参数)
            object instance = Activator.CreateInstance(targetType);

            // 推荐:转为接口调用(需要确保目标类型实现了接口)
            if (instance is IBusinessService service)
            {
                service.Execute();
            }
            else
            {
                // 备选:用反射调用方法(如果没有接口约束)
                MethodInfo executeMethod = targetType.GetMethod("Execute");
                executeMethod?.Invoke(instance, null);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"动态加载类型失败:{ex.Message}");
        }
    }
}

关键注意事项

  • 程序集路径:确保你的类库程序集在主应用的可搜索路径中(比如主项目的bin/Debug目录,或者通过项目引用、NuGet包引用自动复制);
  • 强名称程序集:如果你的类库是强名称签名的,配置字符串中的程序集名称需要包含版本、公钥令牌等信息(格式类似MyOrg.MyApp.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxx);
  • 构造函数:如果目标类型没有默认无参构造函数,需要在Activator.CreateInstance中传入对应的构造参数;
  • 异常处理:动态加载过程中可能出现程序集找不到、类型不存在、实例化失败等异常,一定要做好捕获和处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:37:36