无需查询即可执行 MediatR 请求
Execture MediatR request without query
我有一个 class ProductService.cs
看起来像:
public class ProductService : IProductService
{
private readonly IMediator _mediator;
public ProductService(IMediator mediator)
{
_mediator = mediator;
}
public async Task<IQueryable<Models.Product>> GetActiveProducts()
{
var products = await _mediator.Send(new FindProducts);
return products.Where(product => product.Status.Id == (int)ProductStatusEnum.Active);
}
}
然后我的 FindProducts
看起来像这样:
public class FindProducts
{
public class Handler : IRequest<IQueryable<Models.Product>>
{
private readonly ApplicationDbContext _dbContext;
public Handler(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public IQueryable<Models.Product> Handle()
{
return _dbContext.Products
.Select(p => new Models.Product
{
Name = p.Name,
Status = new ProductStatus
{
Id = p.Status.Id,
Status = p.Status.Status
}
})
.AsQueryable();
}
}
}
然而,当我遇到构建错误时,这不会编译 A new expression requires (), [], or {} after type
我在整个网络上进行了搜索,但找不到任何关于如何发送 MediatR 请求而不发送 [=15] 的示例或文档=] 理想情况下,无论产品数据如何,这都会获得所有产品。
我是不是漏掉了什么?
你需要把它分离出来,你混合了Mediatr接口,例如:
public class FindProducts : IRequest<IQueryable<Models.Product>>
{}
public class FindProductsHandler : IRequestHandler<FindProducts,IQueryable<Models.Product>>
{}
然后通过以下方式调用它:
var query = new FindProducts();
var products = await _mediator.Send(query);
我有一个 class ProductService.cs
看起来像:
public class ProductService : IProductService
{
private readonly IMediator _mediator;
public ProductService(IMediator mediator)
{
_mediator = mediator;
}
public async Task<IQueryable<Models.Product>> GetActiveProducts()
{
var products = await _mediator.Send(new FindProducts);
return products.Where(product => product.Status.Id == (int)ProductStatusEnum.Active);
}
}
然后我的 FindProducts
看起来像这样:
public class FindProducts
{
public class Handler : IRequest<IQueryable<Models.Product>>
{
private readonly ApplicationDbContext _dbContext;
public Handler(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public IQueryable<Models.Product> Handle()
{
return _dbContext.Products
.Select(p => new Models.Product
{
Name = p.Name,
Status = new ProductStatus
{
Id = p.Status.Id,
Status = p.Status.Status
}
})
.AsQueryable();
}
}
}
然而,当我遇到构建错误时,这不会编译 A new expression requires (), [], or {} after type
我在整个网络上进行了搜索,但找不到任何关于如何发送 MediatR 请求而不发送 [=15] 的示例或文档=] 理想情况下,无论产品数据如何,这都会获得所有产品。
我是不是漏掉了什么?
你需要把它分离出来,你混合了Mediatr接口,例如:
public class FindProducts : IRequest<IQueryable<Models.Product>>
{}
public class FindProductsHandler : IRequestHandler<FindProducts,IQueryable<Models.Product>>
{}
然后通过以下方式调用它:
var query = new FindProducts();
var products = await _mediator.Send(query);