我想在发生各种身份事件时引发事件(例如,添加用户和使用userManager)。我对其他实体做得很好,但由于用户实体继承自IdentityUser,我需要一些关于如何使用它的指导。
例如,我可以很好地使用baseEntity的一个实体:public class Vehicle : BaseEntity
{
...
}
BaseEntity:
public abstract class BaseEntity
{
public string Id { get; set; }
private readonly List<BaseEvent> _domainEvents = new();
[NotMapped]
public IReadOnlyCollection<BaseEvent> DomainEvents => _domainEvents.AsReadOnly();
public void AddDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Add(domainEvent);
}
public void RemoveDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Remove(domainEvent);
}
public void ClearDomainEvents()
{
_domainEvents.Clear();
}
}
但是在ApplicationUser实体中,我不能使用这个基本实体来实现事件,因为ApplicationUser类继承自IdentityUser类!
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FatherName { get; set; }
}
我如何使用IdentityUser和BaseEntity事件发生在ApplicationUser类?
你可以这样分开它们:具有Id
的实体的接口public interface BaseId<T> where T : class
{
public T Id { get; set; }
}
具有域事件的实体接口
public interface EntityWithDomainEvent
{
IReadOnlyCollection<BaseEvent> DomainEvents { get; }
void AddDomainEvent(BaseEvent domainEvent);
void RemoveDomainEvent(BaseEvent domainEvent);
void ClearDomainEvents();
}
一个抽象类来包装它以便其他实体从
继承public abstract class BaseEntity : BaseId<string>,EntityWithDomainEvent
{
public string Id { get; set; }
private readonly List<BaseEvent> _domainEvents = new();
public IReadOnlyCollection<BaseEvent> DomainEvents => _domainEvents.AsReadOnly();
public void AddDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Add(domainEvent);
}
public void RemoveDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Remove(domainEvent);
}
public void ClearDomainEvents()
{
_domainEvents.Clear();
}
}
最后是你的ApplicationUser
public class ApplicationUser : IdentityUser,EntityWithDomainEvent
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FatherName { get; set; }
private readonly List<BaseEvent> _domainEvents = new();
public IReadOnlyCollection<BaseEvent> DomainEvents => _domainEvents.AsReadOnly();
public void AddDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Add(domainEvent);
}
public void RemoveDomainEvent(BaseEvent domainEvent)
{
_domainEvents.Remove(domainEvent);
}
public void ClearDomainEvents()
{
_domainEvents.Clear();
}
}