- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用Asp.Net核心控制台应用程序和Entiy Framework核心和工作单元存储库模式。当我使用多线程功能时,出现以下错误:
DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
public interface IUnitOfWork : IDisposable
{
void Commit();
ApplicationDbContext GetContext();
}
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _applicationDbContext;
public UnitOfWork(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public void Commit()
{
try
{
_applicationDbContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public ApplicationDbContext GetContext()
{
return _applicationDbContext;
}
public void Dispose()
{
_applicationDbContext.Dispose();
}
}
public interface IGenericRepository<T>
where T : class, IEntity
{
List<T> GetAll(Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedEnumerable<T>> orderBy = null,
string includeProperties = "");
T FindSingle(int id);
T FindBy(Expression<Func<T, bool>> predicate, string includeProperties = "");
void Add(T toAdd);
void Update(T toUpdate);
void Delete(int id);
void Delete(T entity);
}
public class GenericRepository<T> : IGenericRepository<T>
where T : class, IEntity
{
private readonly IUnitOfWork _unitOfWork;
public GenericRepository(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public virtual List<T> GetAll(Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedEnumerable<T>> orderBy = null,
string includeProperties = "")
{
IQueryable<T> query = _unitOfWork.GetContext().Set<T>();
if (filter != null)
{
query = query.Where(filter);
}
foreach (string includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
public virtual T FindSingle(int id)
{
return _unitOfWork.GetContext().Set<T>().Find(id);
}
public virtual T FindBy(Expression<Func<T, bool>> predicate, string includeProperties = "")
{
IQueryable<T> query = _unitOfWork.GetContext().Set<T>();
foreach (string includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
return query.Where(predicate).FirstOrDefault();
}
public virtual void Add(T toAdd)
{
_unitOfWork.GetContext().Set<T>().Add(toAdd);
}
public virtual void Update(T toUpdate)
{
_unitOfWork.GetContext().Entry(toUpdate).State = EntityState.Modified;
}
public virtual void Delete(int id)
{
T entity = FindSingle(id);
_unitOfWork.GetContext().Set<T>().Remove(entity);
}
public virtual void Delete(T entity)
{
_unitOfWork.GetContext().Set<T>().Remove(entity);
}
}
public interface IUserService
{
void CreateUser(UserEntity userEntity, bool commit = false);
}
public class UserService : IUserService
{
private readonly IGenericRepository<UserEntity> _userRepository;
private readonly IUnitOfWork _unitOfWork;
public UserService(IUnitOfWork unitOfWork, IGenericRepository<UserEntity> userRepository)
{
_unitOfWork = unitOfWork;
_userRepository = userRepository;
}
public void CreateUser(UserEntity userEntity, bool commit = false)
{
try
{
_userRepository.Add(userEntity);
if (commit)
_unitOfWork.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class Program
{
public static ServiceProvider ServiceProvider;
static void Main(string[] args)
{
InitializeIoc();
Task.Run(() => { FuncA(); });
Task.Run(() => { FuncB(); });
Console.ReadLine();
}
private static void InitializeIoc()
{
ServiceProvider = new ServiceCollection()
.AddDbContext<ApplicationDbContext>()
.AddTransient<IUnitOfWork, UnitOfWork>()
.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>))
.AddTransient<IUserService, UserService>()
.BuildServiceProvider();
}
private static void FuncA()
{
var userService = ServiceProvider.GetService<IUserService>();
for (int i = 0; i < 100; i++)
{
userService.CreateUser(new UserEntity { FirstName = "FuncA_" + Guid.NewGuid(), LastName = "Last", CreatedDate = DateTime.Now }, false);
}
}
private static void FuncB()
{
var userService = ServiceProvider.GetService<IUserService>();
for (int i = 0; i < 100; i++)
{
userService.CreateUser(new UserEntity { FirstName = "FuncB_" + Guid.NewGuid(), LastName = "Last", CreatedDate = DateTime.Now }, false);
}
}
}
最佳答案
问题是使用的AddDbContext
向ApplicationDbContext
注册了ServiceLifetime.Scoped
,但是您没有创建范围,因此它有效地作为单例工作,因此被多个线程并发共享和访问,这导致了所讨论的异常(并且可能还有许多其他原因,因为DbContext
不是线程安全)。
解决方案是使用范围,例如调用CreateScope
并使用返回的对象ServiceProvider
属性来解析服务:
private static void FuncA()
{
using (var scope = ServicePropvider.CreateScope())
{
var userService = scope.ServiceProvider.GetService<IUserService>();
// Do something ...
}
}
private static void FuncB()
{
using (var scope = ServicePropvider.CreateScope())
{
var userService = scope.ServiceProvider.GetService<IUserService>();
// Do something ...
}
}
关于multithreading - 控制台应用程序-DbContext实例不能在OnConfiguring内部使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603280/
我已经开始研究使用 Identity 框架的现有 ASP.NET Core 项目。该应用程序使用单个数据库。出于某种原因,应用程序使用两个独立的数据库上下文 - 一个派生自 IdentityDbCon
我刚刚下载了EntityFramework.dll v4.3。我发现了许多比较 DbContext 与 ObjectContext 的问题。但其中大部分是 2010 年或 2011 年初的。 我想阅读
我想做什么 public void SomeTestMethod(){ var person = this.PersonManager.Get(new Guid("someguid"));
在我的应用程序中,我刚刚将 EntityFramework 更新到版本 6.0.2,现在我遇到了一些错误,这是我在更新我的应用程序之前没有发现的。 我有一个从 IdentityDbContext 类继
我正在处理一个大型项目,每个 DbContext 下有 50 多个 DbContext 和 100 多个 DbSet。 每个 DbContext 都由一个单独的团队处理,他们根据他们的要求/更改添加/
我是 WPF 的初学者。我想知道 dbcontext.Add 和 dbcontext.AddObject 之间有什么区别。 private void AddButton_Click(object se
我正在使用 MVC .Net。通常,每当我需要查询数据库时,我总是使用类似下面的方法来创建一个实例: using (EntitiesContext ctx = new EntitiesContext(
我在 HomeController 中有一个方法,我试图通过 URL 访问它,如下所示: http://localhost/web/home/GetSmth 第一次工作,但刷新页面后,我收到此错误:
在我的 Controller 中,我有这个 private readonly DbContext _context; public CountryController(DbContext contex
我正在寻找一种回滚实体更改的方法。我遇到了this answer它显示了如何设置实体状态,但我想知道如果我只是处理我的 dbContext 实例而不调用 dbContext.SaveChanges()
在我的项目中,我使用entity framework 7 和asp.net mvc 6\asp.net 5。我想为自己的模型创建 CRUD 我怎样才能做得更好: 使用 Controller 中的 db
我正在使用 Asp.Net Core 2.1 开发 Web 应用程序。在我使用脚手架添加新身份后,它为我生成了这些代码: IdentityStartup.cs 中生成的代码 [assembly:Hos
一旦我解决了one issue与 IBM.EntityFrameworkCore ,另一个出现了。对于 DB2 和他们的 .NET 团队来说,一切都是那么艰难和痛苦...... 问题:我在同一个 VS
我正在尝试创建一个播种用户和角色数据的类。 我的播种数据类(class)采用RoleManager构造函数参数 public class IdentityDataSeeder { private
我正在使用 .NET Core 2.1 构建 Web API。这将作为 Azure Web 应用程序托管。我想将数据库连接字符串保留在 Azure Key Vault 中。这是我放入 Startup.
当使用像 MySQL 这样的网络数据库时,DbContext 应该是短暂的,但是根据 https://www.entityframeworktutorial.net/EntityFramework4.
我有一个直接调用的 Controller 操作,但抛出了这个错误: The operation cannot be completed because the DbContext has been d
我在 Visual Studio 中使用默认的 ASP.Net MVC 模板。我正在使用在模板中为我创建的 ASP.Net 身份代码。我希望我使用的 DBContext 了解 ApplicationU
我有一个软件产品,它的数据库是在 SQLServer 上创建的,表名和列名是由开发团队定义的,然后使用 Database First 方法将模型导入 Visual Studio,现在我们正在为其他公司
我正在使用 EFCore 加载“用户”实体和用户制作的相关“订单”。 我有一个构造函数(来自真实代码的简化示例),它使用 id=1 加载用户并实现一个命令来更新 LoadedUser 实体中的更改。但
我是一名优秀的程序员,十分优秀!