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

C# Web应用运行时修改AssemblyInfo.cs后自动重载方案咨询

解决运行时自动加载动态依赖的问题

首先要明确:AssemblyInfo.cs是编译阶段的配置文件,它用来定义程序集的元数据(版本、标题、版权等),运行时修改它不会直接影响正在运行的程序——本地开发时Visual Studio提示重载后生效,本质是VS重新编译了项目、生成了新的程序集并重启了应用进程。这种依赖编译+手动重载的方式,完全不适合服务器无人值守的场景。

你的核心需求是运行时动态添加并加载依赖项,无需手动干预,正确的做法是放弃修改AssemblyInfo.cs的思路,改用以下两种方案:

方案一:直接动态加载程序集

如果你的依赖项是独立的dll文件,从数据库获取到dll的本地存储路径后,直接用.NET提供的反射API加载即可,全程无需修改任何编译时文件:

// 从数据库获取依赖dll的本地路径
string dllLocalPath = FetchDllPathFromDatabase();

// 动态加载程序集
Assembly dynamicAssembly = Assembly.LoadFrom(dllLocalPath);

// 按需使用程序集中的类型(示例)
Type targetType = dynamicAssembly.GetType("YourNamespace.YourClass");
if (targetType != null)
{
    object instance = Activator.CreateInstance(targetType);
    // 调用类中的方法
    MethodInfo method = targetType.GetMethod("YourMethod");
    method?.Invoke(instance, null);
}

这种方式的优势是简单直接,适合一次性加载静态依赖的场景。

方案二:用AppDomain实现热重载

如果需要动态更新已经加载的依赖(比如替换旧版本的dll),可以通过AppDomain隔离加载逻辑:因为已加载的程序集无法直接卸载,只能通过卸载整个AppDomain来实现“重载”。

  1. 首先定义一个跨AppDomain的加载器(必须继承MarshalByRefObject):
public class RemoteAssemblyLoader : MarshalByRefObject
{
    public void LoadAndRunAssembly(string dllPath)
    {
        Assembly assembly = Assembly.LoadFrom(dllPath);
        // 在这里执行程序集的业务逻辑
        Type workerType = assembly.GetType("YourNamespace.WorkerClass");
        var worker = Activator.CreateInstance(workerType);
        workerType.GetMethod("DoWork")?.Invoke(worker, null);
    }
}
  1. 然后在主程序中创建和管理AppDomain:
// 创建新的AppDomain用于加载动态程序集
var domainSetup = new AppDomainSetup
{
    ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
    PrivateBinPath = "DynamicDlls" // 存放动态dll的目录
};
AppDomain dynamicDomain = AppDomain.CreateDomain("DynamicDependencyDomain", null, domainSetup);

// 在新AppDomain中加载程序集并执行
var loader = (RemoteAssemblyLoader)dynamicDomain.CreateInstanceAndUnwrap(
    typeof(RemoteAssemblyLoader).Assembly.FullName,
    typeof(RemoteAssemblyLoader).FullName);
loader.LoadAndRunAssembly(dllLocalPath);

// 当需要更新依赖时,卸载旧的AppDomain,再创建新的加载新版本dll
AppDomain.Unload(dynamicDomain);
// 重复上述步骤加载新dll

关键提醒

不要试图通过修改AssemblyInfo.cs来实现动态依赖加载:

  • 该文件仅在编译阶段生效,运行时修改后必须重新编译才能生成新的程序集,服务器环境通常没有Visual Studio或完整的编译工具链。
  • 即使实现了自动编译,也需要重启应用进程才能加载新程序集,这比直接动态加载的成本高得多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:05:23