首页 > 其他分享 >net core+mediatr+EF实现事件触发

net core+mediatr+EF实现事件触发

时间:2023-06-05 22:24:16浏览次数:30  
标签:core mediatr void EF dbContext NetOptions new using public

参考杨中科的教程

1.先添加接口

using MediatR;

namespace NetOptions.Entities;

public interface IDomainEnvent
{
    void AddNotification(INotification notification);
    IEnumerable<INotification> GetNotifications();
    void ClearNotifications();
}

2.添加抽象基类

using MediatR;

namespace NetOptions.Entities;

public abstract class BaseEntity : IDomainEnvent
{
    private readonly IList<INotification> notifications = new List<INotification>();
    public void AddNotification(INotification notification)
    {
        notifications.Add(notification);
    }

    public void ClearNotifications()
    {
        notifications.Clear();
    }

    public IEnumerable<INotification> GetNotifications()
    {
        return notifications;
    }
}

3 实体类添加相应方法,变成充血模型

using NetOptions.Entities;
using NetOptions.Entities.Events;

public class User : BaseEntity
{
    public long Id{get;set;}
    public string Name{get;set;}

    public User(string name)
    {
        AddNotification(new UserAddNotif(name));
        this.Name = name;
    }

    public void UpdateName(string newName)
    {
        AddNotification(new UpdateUserNotif(this.Name,newName));
        this.Name = newName;
    }
}

4.修改DBContext.添加相应事件

using Microsoft.EntityFrameworkCore;
using NetOptions.Entities;
using MediatR;
using Pomelo.EntityFrameworkCore.MySql;

namespace NetOptions.DbContexts;

public class UserDbContext : DbContext
{
    private readonly IMediator _meditor;

    public UserDbContext(IMediator meditor)
    {
        _meditor = meditor;
    }

    public DbSet<User> Users { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        ServerVersion server =  ServerVersion.Parse("8.0.27");
        optionsBuilder.UseMySql("Data Source=127.0.0.1;port=3306;Initial Catalog=FBTest;user id=root;password=ybdai930728;Character Set=utf8",server);
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public override int SaveChanges()
    {
        var baseDomainNotifs = this.ChangeTracker.Entries<IDomainEnvent>()
            .Where(w => w.Entity.GetNotifications().Any());
        var baseDomainNotifss = baseDomainNotifs.SelectMany(s => s.Entity.GetNotifications()).ToList();
        baseDomainNotifs.ToList().ForEach(c => c.Entity.ClearNotifications());
        foreach(var notif in baseDomainNotifss){
            _meditor.Publish(notif);
        }

        return base.SaveChanges();
    }
}

5,添加action

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NetOptions.DbContexts;

namespace NetOptions.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly UserDbContext _dbContext;

    public WeatherForecastController(ILogger<WeatherForecastController> logger,UserDbContext dbContext)
    {
        _logger = logger;
        _dbContext = dbContext;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        User user = new User("DYB");
        _dbContext.Users.Add(user);
        user.UpdateName("超级塞牙人");
        _dbContext.SaveChanges();

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

6,添加一些注册

builder.Services.AddMediatR(c=>c.RegisterServicesFromAssembly(Assembly.GetEntryAssembly()));
builder.Services.AddDbContext<UserDbContext>();

7 实现效果 调用 https://localhost:7245/WeatherForecast接口,打印的日志如下:

 

标签:core,mediatr,void,EF,dbContext,NetOptions,new,using,public
From: https://www.cnblogs.com/Insist-Y/p/17459076.html

相关文章

  • 手把手教你AspNetCore WebApi:Swagger(Api文档)
    前言小明已经实现“待办事项”的增删改查,并美滋滋向负责前端的小红介绍Api接口,小红很忙,暂时没有时间听小明介绍,希望小明能给个Api文档。对于码农小明来说能不写文档就尽量不要写,不过这也难不倒小明,他知道Swagger不仅可以自动生成Api文档,并还可以用Swagger进行接口测试。Swagger是什......
  • 手把手教你AspNetCore WebApi:数据验证
    前言小明最近又遇到麻烦了,小红希望对接接口传送的数据进行验证,既然是小红要求,那小明说什么都得满足呀,这还不简单嘛。传统验证[HttpPost]publicasyncTask<ActionResult<Todo>>PostTodo(Todotodo){if(string.IsNullOrEmpty(todo.Name)){returnOk("名称不......
  • 手把手教你AspNetCore WebApi:Serilog(日志)
    前言小明目前已经把“待办事项”功能实现了,API文档也搞定了,但是马老板说过,绝对不能让没有任何监控的项目上线的。Serilog是什么?在.NET使用日志框架第一时间会想到NLog或是Log4Net,Serilog是这几年快速崛起的Log框架之一,Serilog是以Structuredlogging为基础进行设计,透过loggingAP......
  • 手把手教你AspNetCore WebApi:缓存(MemoryCache和Redis)
    前言这几天小明又有烦恼了,系统上线一段时间后,系统性能出现了问题,马老板很生气,叫小明一定要解决这个问题。性能问题一般用什么来解决呢?小明第一时间想到了缓存。什么是缓存缓存是实际工作中非常常用的一种提高性能的方法。缓存可以减少生成内容所需的工作,从而显著提高应用程序的性能......
  • ASP.NET Core MVC 项目在IIS中部署
    一、vs中把MVC项目以文件系统发布、设置保存的路径二、安装.NETCore3.1Runtime网址:https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-3.1.5-windows-x64-installer 三、安装AspNetCoreModule网址:https://dotnet.microsoft.com/download/dotne......
  • 手把手教你AspNetCore WebApi:增删改查
    前言小明已经创建与运行了WebApi项目,了解项目结构有哪些组成,并学会了怎么发布到IIS。基础已经建好,从现在开始要真正实现待办事项的功能了。新建表CREATETABLE[dbo].[Todo]( [Id][uniqueidentifier]NOTNULL, [Name][nvarchar](100)NULL,CONSTRAINT[PK_Todo]PRIMARYKEY......
  • 手把手教你AspNetCore WebApi:认证与授权
    前言这几天小明又有烦恼了,之前给小红的接口没有做认证授权,直接裸奔在线上,被马老板发现后狠狠的骂了一顿,赶紧让小明把授权加上。赶紧Baidu一下,发现大家都在用JWT认证授权,这个倒是挺适合自己的。什么是TokenToken是服务端生成的一串字符串,以作客户端进行请求的一个令牌,当第一次登录后......
  • Asp.net core中间件实现原理及用法解说
    简述asp.netcore中间件的实现思路 一次http请求的过程,就是对一个Request请求进行若干次逻辑处理,并最终设置Response的过程。从代码的实现维度看,由于Request和Response都在HttpContext里,可将此过程表示为“以一个httpContext为输入的委托函数”,即delegateTaskRequestDelegate(Ht......
  • asp.net core 中的路由
          ......
  • Net Core - EntityFrameWorkCore
    一 mac执行dotnetef报错dotnettoolinstall--globaldotnet-ef二 1.增加迁移dotnetefmigrationsadd名字--contextDBContext名字2.删除最近一次的迁移  >dotnetefmigrationsremove--contextDBContext名字3.更新数据库  >dotnetefdatabaseup......