You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Framework/Connected.Services/ServiceOperation.cs

95 lines
1.6 KiB

2 years ago
using System.Collections.Concurrent;
using Connected.Interop;
using Connected.ServiceModel;
using Connected.ServiceModel.Transactions;
namespace Connected.Services;
public abstract class ServiceOperation<TArgs> : IServiceOperation<TArgs>, ITransactionClient, IOperationState
where TArgs : IDto
{
private TArgs _arguments;
protected ServiceOperation()
{
State = new();
}
private ConcurrentDictionary<string, object?> State { get; }
public TArgs Arguments
{
get => _arguments;
protected set
{
if (value is null)
throw new ArgumentException(nameof(Arguments));
_arguments = value;
}
}
public TEntity? SetState<TEntity>(TEntity? entity)
{
var key = typeof(TEntity).FullName;
if (string.IsNullOrEmpty(key))
return entity;
State.AddOrUpdate(key, entity, (existing, @new) =>
{
return @new;
});
return entity;
}
public TEntity? GetState<TEntity>()
{
var key = typeof(TEntity).FullName;
if (string.IsNullOrEmpty(key))
return default;
if (!State.TryGetValue(key, out object? result))
return default;
if (TypeConversion.TryConvert(result, out TEntity? entity))
return entity;
return default;
}
async Task ITransactionClient.Commit()
{
await OnCommitting();
await OnCommitted();
}
async Task ITransactionClient.Rollback()
{
await OnRollingBack();
await OnRolledBack();
}
protected virtual async Task OnCommitted()
{
await Task.CompletedTask;
}
protected virtual async Task OnRolledBack()
{
await Task.CompletedTask;
}
protected virtual async Task OnCommitting()
{
await Task.CompletedTask;
}
protected virtual async Task OnRollingBack()
{
await Task.CompletedTask;
}
}