jasontaylordev / NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.
MIT License
5k stars 1.59k forks source link

Suggestion: Request with record type #304

Closed acesteb closed 2 years ago

acesteb commented 2 years ago

Suggestion for Request record type. What do you guys think?

1) Creating the request using record type public record Ping(int Id): IRequest<string>;

public record Ping(int Id) : IRequest<string> 
{
  public class Handler : IRequestHandler<Ping, string>
  {
      public Task<string> Handle(Ping request, CancellationToken cancellationToken)
      {
          Console.WriteLine(request.Id);
          return Task.FromResult("Pong");
      }
  }
}

vs

public record Ping : IRequest<string>
{
   public Ping(int Id) 
   {
        Id = id;
   }
   public int Id {get;}

    public class Handler : IRequestHandler<Ping, string>
    {
        public Task<string> Handle(Ping request, CancellationToken cancellationToken)
        {
            Console.WriteLine(request.Id);
            return Task.FromResult("Pong");
        }
    }
}

Record types provide you with immutable objects. In terms of DDD, records types saves you some typing regarding internal setters and a constructor.