无法访问 class 中扩展 Hub 的 DbContext
Can't access DbContext in class that extends Hub
我正在尝试访问我的 SignalR Hub 中的 DbContext,但它一直抛出此异常:
{"Value cannot be null. (Parameter 'unitOfWork')"}
不知道是什么问题。这是我的代码:
public class MyHub : Hub
{
private readonly IRepository<MyTable, long> _repository;
public MyHub (IRepository<MyTable, long> repository)
{
_repository = repository;
}
public async Task Get(TestDto testDto)
{
try
{
var myData = await _repository.GetDbContext().Set<MyTable>()
.Include(x => x.obj1)
.ThenInclude(x => x.list1)
.ThenInclude(x => x.obj2)
.ToListAsync();
await Clients.All.SendAsync("Get", myData);
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.InnerException.Message.ToString());
}
}
}
注意:我正在使用 ASP.NET 样板框架(.NET 核心 3.1 和 Angular)
添加 [UnitOfWork]
属性并使其成为 virtual
方法:
[UnitOfWork]
public virtual async Task Get(TestDto testDto)
{
// ...
}
或者您可以注入 IUnitOfWorkManager
以显式开始 UnitOfWork
:
public async Task Get(TestDto testDto)
{
using (var uow = UnitOfWorkManager.Begin())
{
try
{
var myData = await _repository.GetDbContext().Set<MyTable>()
.Include(x => x.obj1)
.ThenInclude(x => x.list1)
.ThenInclude(x => x.obj2)
.ToListAsync();
await Clients.All.SendAsync("Get", myData);
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.InnerException.Message.ToString());
}
}
}
我正在尝试访问我的 SignalR Hub 中的 DbContext,但它一直抛出此异常:
{"Value cannot be null. (Parameter 'unitOfWork')"}
不知道是什么问题。这是我的代码:
public class MyHub : Hub
{
private readonly IRepository<MyTable, long> _repository;
public MyHub (IRepository<MyTable, long> repository)
{
_repository = repository;
}
public async Task Get(TestDto testDto)
{
try
{
var myData = await _repository.GetDbContext().Set<MyTable>()
.Include(x => x.obj1)
.ThenInclude(x => x.list1)
.ThenInclude(x => x.obj2)
.ToListAsync();
await Clients.All.SendAsync("Get", myData);
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.InnerException.Message.ToString());
}
}
}
注意:我正在使用 ASP.NET 样板框架(.NET 核心 3.1 和 Angular)
添加 [UnitOfWork]
属性并使其成为 virtual
方法:
[UnitOfWork]
public virtual async Task Get(TestDto testDto)
{
// ...
}
或者您可以注入 IUnitOfWorkManager
以显式开始 UnitOfWork
:
public async Task Get(TestDto testDto)
{
using (var uow = UnitOfWorkManager.Begin())
{
try
{
var myData = await _repository.GetDbContext().Set<MyTable>()
.Include(x => x.obj1)
.ThenInclude(x => x.list1)
.ThenInclude(x => x.obj2)
.ToListAsync();
await Clients.All.SendAsync("Get", myData);
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.InnerException.Message.ToString());
}
}
}