Use _guidGenerator on AggregatedRoot model

40 Views Asked by At

I have an EF model like this:

public class Test : AuditedAggregateRoot<Guid>, IMultiTenant, IProcessibleType
{
    public IList<Test> EventHistory { get; set; }
    private readonly IGuidGenerator _guidGenerator;
    public Guid? TenantId { get; set; }

 public Status Status { get { return this._Status; } 
 set { 
     if(this._Status != value)
         {
           
                 this.AddEventHistory(EventType.StatusChange, $"Status updated from {this._Status} to {value}.", null);
             this._Status = value;
         }
     } }

 public void AddEventHistory(EventType eventType, string description)
 {
     var event = new Test(_guidGenerator.Create(), this.Id, eventType, description);
     this.EventHistory.Add(event);
 }
}

As you can see, I tried to use _guidGenerator.Create(), but this always returns a null exception; how can I use an ABP guid generator on an EF entity?

1

There are 1 best solutions below

3
aaron On BEST ANSWER

An AggregateRoot should not have a reference to an IGuidGenerator.

Use a DomainService:

public class Test : AuditedAggregateRoot<Guid>, IMultiTenant, IProcessibleType
{
    public IList<Test> EventHistory { get; set; }
    public Guid? TenantId { get; set; }

    public Status Status
    {
        get { return this._Status; } 
        internal set { this._Status = value; }
    }
}

public class TestManager : DomainService
{
    public void UpdateStatus(Test test, Status status)
    {
        if (test.Status != status)
        {
            this.AddEventHistory(test, EventType.StatusChange, $"Status updated from {test.Status} to {status}.")
            test.Status = status;
        }
    }

    protected void AddEventHistory(Test test, EventType eventType, string description)
    {
        var event = new Test(GuidGenerator.Create(), test.Id, eventType, description);
        test.EventHistory.Add(event);
    }
}

Usage:

// test.Status = status;                  // Change this
_testManager.UpdateStatus(test, status);  // to this