在Program里面注册服务
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(DBTransactionBehavior<,>));这里链接数据库我们做一个新增Command里面的testContext就是数据库上下文我这里是从数据库直接生成的 WyyDbContext继承testContext
using MediatApi.Entity;using MediatR;namespace MediatApi.Application.Command{ public class CusCreateCommand:IRequest<int> { public string? Name { get; set; } public int? Age { get; set; } } public class CusCreateCommandHandler : IRequestHandler<CusCreateCommand, int> { private readonly testContext _db; public CusCreateCommandHandler(testContext db) { _db = db; } public async Task<int> Handle(CusCreateCommand request, CancellationToken cancellationToken) { Cu c = new() { Name = request.Name, Age = request.Age, }; _db.Cus.Add(c); Console.WriteLine("执行处理++++++++++++++++++++++++++++++++++"); return await _db.SaveChangesAsync(); } }}为了增加对比性 我也新建了一个传统的services来新增Cus
using MediatApi.Entity;namespace MediatApi.services{ public interface ICusService { Task<int> AddAsync(); } public class CusService : ICusService { private readonly testContext _db; public CusService(testContext db) { _db = db; } public async Task<int> AddAsync() { Cu c = new() { Name = "wyy", Age = 18 }; _db.Cus.Add(c); return await _db.SaveChangesAsync(); } }}
经验总结扩展阅读
- 常用Python库整理
- 2023年1月24日建造寺庙好吗 2023年1月24日建造寺庙行吗
- 中式装修风格怎么搭配更好看 中式风格装修注意事项有哪些
- 2023年1月24日修筑堤坝好吗 2023年1月24日是修筑堤坝的黄道吉日吗
- 2023年1月24日粉刷墙壁好吗 2023年1月24日是粉刷墙壁的黄道吉日吗
- 2023年1月24日厨房移位好吗 2023年1月24日厨房移位行吗
- 加拿大高中排名 加拿大高中排名
- 2023中秋祝福语送客户
- 2023中秋祝福语送领导
- 2023送给领导的中秋祝福语