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

ASP.NET Core实现SOAP服务注入跨项目DbContext时出现生命周期错误

问题解决方法

这个错误由两个核心原因导致,按以下步骤修改即可修复:

步骤1:确认项目依赖

首先确保当前SOAP服务项目已经完成两个前置配置:

  • 已添加同解决方案下OtherProject的项目引用
  • 已安装EF Core对应版本的NuGet包:Microsoft.EntityFrameworkCore、对应数据库的驱动包(如SQL Server对应Microsoft.EntityFrameworkCore.SqlServer)

步骤2:注册DbContext并调整服务生命周期

EF Core的DbContext默认是**作用域(Scoped)**生命周期,而你当前把IMyTestService注册为单例(Singleton),直接注入会出现生命周期不匹配问题,同时你还没有将MyContext注册到DI容器。
修改Startup.cs的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
{
    // 注册MyContext,替换为你实际使用的数据库和连接字符串
    services.AddDbContext<MyContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    services.AddSoapCore();
    // 把服务生命周期从Singleton改为Scoped,和DbContext生命周期匹配
    services.TryAddScoped<IMyTestService, MyTestService>();
    services.AddMvc();
}

同时在项目的appsettings.json中添加数据库连接字符串配置:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=你的数据库地址;Database=你的库名;User Id=用户名;Password=密码;TrustServerCertificate=True;"
  }
}

步骤3:同步更新服务契约

你修改了服务实现新增了GetInfoById方法,需要同步在IMyTestService接口中添加对应的操作契约标记,否则方法不会被SOAP服务暴露:

[ServiceContract]
public interface IMyTestService
{
    [OperationContract]
    string TestMethod(string s);
    
    // 新增对应方法的契约标记
    [OperationContract]
    Info GetInfoById(int id);
}

可选:如果必须保留服务为单例

如果你的业务场景要求IMyTestService必须是单例生命周期,不要直接注入MyContext,改为注入IServiceScopeFactory手动创建作用域获取上下文:

public class MyTestService: IMyTestService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public MyTestService(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public Info GetInfoById(int id)
    {
        using var scope = _scopeFactory.CreateScope();
        var context = scope.ServiceProvider.GetRequiredService<MyContext>();
        return context.Info.FirstOrDefault(c => c.Id == id);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:57:01