首页 > 解决方案 > 简单注射器 - 生活方式不匹配

问题描述

我正在使用工作单元模式进行转换。我创建了一个处理连接、提交、回滚工作的 DbContext。

在我的数据访问和业务层类中,我通过构造函数注入 IDbContext。

public TestDAL(IDbContext dbContext) : base(dbContext) {}

public TestService(IDbContext dbContext, ITestDAL testDAL) {}

我从 autofac 移动了简单的注射器。我得到了一个关于生活方式不匹配的例外。

-[生活方式不匹配] TestService (Async Scoped) 依赖于由 DbContext (Transient) 实现的 IDbContext。

-[生活方式不匹配] TestDAL (Async Scoped) 依赖于由 DbContext (Transient) 实现的 IDbContext。

我将我的 DAL 和服务类注册为作用域,将 DbContext 注册为瞬态。

var ServiceRegistrations =
                from type in Assembly.GetExecutingAssembly().GetTypes()
                where type.Name.EndsWith("Service") && type.IsClass
                from service in type.GetInterfaces()
                select new { service, type };

foreach (var reg in ServiceRegistrations)
{
    container.Register(reg.service, reg.type, Lifestyle.Scoped);
}

container.Register<IDbContext, DbContext>(Lifestyle.Transient);

我读了一些关于 DbContext 应该是瞬态的,它不是线程安全的。另外我认为 DAL 和服务类不需要创建瞬态。我该如何解决这种情况?顺便说一句,这在 autofac 上不是问题。

标签: c#.netdependency-injectionsimple-injector

解决方案


推荐阅读