C#C
C#13mo ago
Zoli

Why event is not triggered correctly?

I have a unit of work pattern and when I save an item I want to fire an event to trigger a sync method in another service class.

Unfortunatelly this way it is not triggered
what am I doing wrong?

/// <summary>
/// Sync agent. It's the sync orchestrator
/// Knows both the Sync Server provider and the Sync Client provider.
/// </summary>
public class SyncAgent
{
    private readonly IUnitOfWork _unitOfWork;

    public SyncAgent(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task SynchronizeAsync()
    {

        Debug.WriteLine("Test saved change");
        // get syncronizable entities
        //var result = await _unitOfWork.GetSyncableItemsAsync();
    }
}

public class UnitOfWork : IUnitOfWork
{

    public event EventHandler EntitySaved;

    public async Task SaveChangesAsync() 
    {
        // saving stuff
        // ...

        // fire event
        EntitySaved?.Invoke(this, new EventArgs());
    }
}

public class RemoteSyncHandler
{
    private readonly SyncAgent _syncAgent;

    public RemoteSyncHandler(SyncAgent syncAgent)
    {
        _syncAgent = syncAgent;
    }

    public void OnChangesSaved(object sender, EventArgs e)
    {
        _syncAgent.SynchronizeAsync().SafeFireAndForget();
    }
}

// in the the Ioc

services.AddScoped<RemoteSyncHandler>(provider =>
{
    var handler = new RemoteSyncHandler(provider.GetRequiredService<SyncAgent>());
    var unitOfWork = provider.GetRequiredService<IUnitOfWork>();

    // Subscribe to the ChangesSaved event
    unitOfWork.EntitySaved += handler.OnChangesSaved;

    return handler;
});
Was this page helpful?