Wie log ich "Wer hat was getan" protokolliert, ohne in jeder Methode BenutzerID hinzuzufügen?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Wie log ich "Wer hat was getan" protokolliert, ohne in jeder Methode BenutzerID hinzuzufügen?

Post by Anonymous »

Ich implementiere eine DDD -App, in der meine Entitäten Domainevents für Prüfungszwecke abgeben. Jede Aktion, die in meinem Board auftritt, sollte etwas bei der DB protokollieren. Im Beispiel brüll probiere ich an, dass jemand den Namen des Boards aktualisiert hat. Dies wirft die Frage auf: Meine Board -Klasse hat rund 10-15 Methoden, und ich müsste in jedem einzelnen von ihnen nur zu Protokollierungszwecken die userID übergeben. Das scheint meiner Meinung nach nicht sehr sauber zu sein-haben Sie alternative Ansätze?

Code: Select all

public class Board : Entity // Entity has domainEvents stuff
{
public Guid Id { get; private set; }
public string Name { get; private set; }

public Board(string name)
{
Id = Guid.NewGuid();
Name = name;
}

// PROBLEM: I want to emit event but don't have userId
public void UpdateName(string newName)
{
Name = newName;

// Missing: "by user {userId}". How to include userId without adding a parameter?
_domainEvents.Add(new BoardUpdatedEvent(Id, $"Name updated to {newName}"));

}
}

public class BoardUpdatedEvent
{
public Guid BoardId { get; }
public string Action { get; } // user X did something

public BoardUpdatedEvent(Guid boardId, string action)
{
BoardId = boardId;
Action = action;
}
}

public class UpdateBoardCommand
{
public Guid BoardId { get; }
public string NewName { get; }
public Guid UserId { get; }

public UpdateBoardCommand(Guid boardId, string newName, Guid userId)
{
BoardId = boardId;
NewName = newName;
UserId = userId;
}
}

// Mediatr simplified stuff
public class UpdateBoardHandler
{
public void Handle(UpdateBoardCommand command)
{
var board = GetBoard(command.BoardId);

board.UpdateName(command.NewName);

foreach (var evt in board.DomainEvents)
{
if (evt is BoardUpdatedEvent boardEvent)
{
Console.WriteLine($"Event: {boardEvent.Action}");
// Currently logs: "Name updated to NewName"
// Want to log: "User X updated name to NewName"
}
}

board.ClearEvents();
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post