You need to enable JavaScript to run this app. 是否可跨项目传递DbContext并封装通用会计逻辑到独立DLL复用
优惠活动
大模型
产品
解决方案
定价
更多

是否可跨项目传递DbContext并封装通用会计逻辑到独立DLL复用

问题解决说明

问题根因

你虽然给泛型参数T加了DbContext, IDbAccountringService的双重约束,但类内部存储数据库上下文的字段、构造函数的入参都声明为了DbContext类型,编译器只会按照声明的DbContext类型解析成员,自然识别不到IDbAccountringService接口定义的Accounts等属性。

修复方案

仅需要调整DbAccountingService<T>的字段和构造函数声明,将类型替换为泛型参数T即可:

public class DbAccountingService<T> where T : DbContext, IDbAccountringService
{
    // 字段类型改为泛型参数T,同时符合双重约束
    T dbContext { get; set; }

    // 构造函数入参也改为T类型
    public DbAccountingService(T dbContext)
    {
        this.dbContext = dbContext;
    }

    public Account[] GetAccounts()
    {
        // 现在编译器可正常识别IDbAccountringService定义的Accounts属性
        return dbContext.Accounts.ToArray();
        // DbContext原生方法也可正常调用
        dbContext.SaveChanges();
    }
}

可选优化(依赖注入适配)

如果要进一步简化调用,可将该泛型服务注册到依赖注入容器,无需手动实例化:

  1. 在站点的Program.cs中添加服务注册:
builder.Services.AddScoped(typeof(DbAccountingService<>));
  1. 控制器直接注入服务即可,无需手动传入Db实例:
[Route("accounting/accounts")]
[ApiController]
public class JournalController : BaseApiController
{
    DbAccountingService<Db> _dbAccountingService;

    public JournalController(DbAccountingService<Db> dbAccountingService, MtGlobals mtGlobals) : base(mtGlobals)
    {
        _dbAccountingService = dbAccountingService;
    }

    [HttpGet("get-accounts")]
    public Account[] GetAccounts()
    {
        return _dbAccountingService.GetAccounts();
    }
}

架构可行性说明

你想要抽离公共会计逻辑到独立DLL的需求完全可行,这套实现模式可以保证不同站点只要让自身的DbContext实现IDbAccountringService接口,就能直接复用Accounting.dll中所有封装好的数据操作逻辑,无需重复开发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:39:02