Events are mainly used to run logic asynchronly to the incoming request. Every event is stored in the database and will be processed by the Subscriber Notifications job.
Every minute will NLess.IO processing the newly events.
public class YourService
{
private readonly IEventAccess _eventAccess;
public YourService(IEventAccess eventAccess)
{
_eventAccess = eventAccess;
}
public bool CreateEvent()
{
var data = new {
yourTestData = true
};
_eventAccess.AddEvent(new EventDataModel()
{
Data = JsonSerializer.Serialize(data),
TimeStamp = DateTime.Now, // Define when the event is outdated and will be deleted by the clean up job
Type = "CustomType" // Free to use any string
});
return true;
}
}
To subscribe to the subscriber notifications, create a new class which is inheriting from IEventSubscriber.
⚠️ Every event will produce a notification only one time.
public class SomeNotificationEventSubscriber : IEventSubscriber
{
public Task<bool> HandleAsync(EventDataModel eventDataModel)
{
if (eventDataModel.Type.Equals("CustomType")) // Recommend for checking the correct type
{
var yourEventData = JsonSerializer.Deserialize<YourDataModel>(eventDataModel.Data, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
...
}
return Task.FromResult(true);
}
}
Add the event subscriber to the services:
services.AddTransient<IEventSubscriber, SomeNotificationEventSubscriber>();
To prevent flooding the database with stored events, events older than a period of time.
{
"NLESS.IO": {
"Events": {
"Enabled": true,
"KeepDuration": 1440
}
}
}
To run events and notification subscribers, this must be set to true
This is the amount of minutes, the events will be stored in the database. 1440 minutes = 24 hours