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

.NET Framework 4.8 Windows服务中EF Core 3.1.32初始化失败求助

解决方案

1. 添加程序集绑定重定向到app.config

Windows服务运行时无法自动处理.NET Standard/.NET Core相关程序集的版本兼容,必须显式配置绑定重定向。在你的服务项目的app.config中添加以下配置:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <!-- 解决System.Runtime版本找不到的问题 -->
    <dependentAssembly>
      <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-4.2.2.0" newVersion="4.0.0.0" />
    </dependentAssembly>
    <!-- 确保Microsoft.Bcl.AsyncInterfaces被正确加载 -->
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.1.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

2. 确保依赖包被正确部署到服务目录

  • 检查服务安装目录下是否存在Microsoft.Bcl.AsyncInterfaces.dll和System.Runtime.dll,如果缺失,手动从项目的bin\Release目录复制过去。
  • 在NuGet包管理器中,将Microsoft.Bcl.AsyncInterfaces和Microsoft.EntityFrameworkCore的复制本地属性设置为True,确保编译时将依赖文件复制到输出目录。

3. 提前加载依赖程序集(可选)

在服务启动时手动加载相关程序集,避免运行时加载失败。修改ServiceBase的OnStart方法:

protected override void OnStart(string[] args)
{
    // 提前加载所需程序集
    Assembly.Load("Microsoft.Bcl.AsyncInterfaces, Version=1.1.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
    Assembly.Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
    
    // 启动WCF宿主及其他业务逻辑
    InitializeWcfHost();
}

4. 禁用EF Core的异步处置功能(临时 workaround)

如果不需要异步处置DbContext,可以在DbContext的配置中禁用相关警告,避免触发IAsyncDisposable的加载:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(YourConnectionString);
    // 忽略异步处置相关的警告,避免加载IAsyncDisposable
    optionsBuilder.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ContextDisposedAsync));
}

问题原因说明

控制台应用运行时依赖Visual Studio的加载上下文,会自动处理部分程序集绑定和依赖加载;而Windows服务作为独立进程运行,没有这个环境支持,必须显式配置绑定重定向并确保所有依赖文件存在于安装目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:37:42