Entity Change Listener
Sometimes you want your application to react when an entity changes, e.g. to update a cache. Confinity offers the IEntityChangeListener interface for this purpose.
Prerequisites
The entity must inherit from ConfinityEntity.
public class Foobar : ConfinityEntity
{
public string Name { get; set; } = null!;
}
Implementation
Inherit from IEntityChangeListener and implement the Handle method.
public class FoobarChangeListenerSimple(IFoobarCacheService foobarCacheService) : IEntityChangeListener
{
public async Task Handle(IEnumerable<IEntityChange> changes)
{
await foobarCacheService.RebuildAsync();
}
}
The Handle method gets invoked with a bunch of IEntityChange instances. You might want to evaluate them as followed.
public class FoobarChangeListenerComplex(IFoobarCacheService foobarCacheService) : IEntityChangeListener
{
public async Task Handle(IEnumerable<IEntityChange> changes)
{
var changesList = changes.ToList();
var idsToInvalidate = changesList
.Where(p => p.IsDeletion)
.Select(p => p.EntityId);
await foobarCacheService.InvalidateAsync(idsToInvalidate);
var idsToCache = changesList
.Where(p => !p.IsDeletion)
.Select(p => p.EntityId);
await foobarCacheService.RebuildAsync(idsToCache);
}
}
Registration
Register the implementation in your module configuration together with one or more entity types you want to monitor.
public void AddModule(IModuleContext module)
{
module.Configure.RegisterChangeListener<FoobarChangeListenerSimple>(typeof(Foobar));
}
Notes
- Listeners are executed in parallel
- On the author instance listeners are triggered by the DbContext
- On public instances listeners are triggered by the replication