49 lines
2.0 KiB
C#
49 lines
2.0 KiB
C#
using Medusa.Core.Attributes;
|
|
using Medusa.Core.Handlers;
|
|
using System.Reflection;
|
|
using System.Xml.Linq;
|
|
|
|
namespace Medusa.Core.Services
|
|
{
|
|
public class HandlerService(IServiceProvider serviceProvider, ILogger<HandlerService> logger) : IHandlerService
|
|
{
|
|
private readonly IServiceProvider _serviceProvider = serviceProvider;
|
|
private readonly ILogger<HandlerService> _logger = logger;
|
|
|
|
public List<Type> Handlers { get; set; } = [];
|
|
|
|
public async Task<XDocument> Handle(string model, string module, string method, XDocument body)
|
|
{
|
|
foreach (var handler in Handlers)
|
|
{
|
|
//Module and service are on the attribute
|
|
var handlerAttribute = handler.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(HandlerAttribute));
|
|
|
|
if (handlerAttribute is null)
|
|
continue;
|
|
|
|
var attributeModule = handlerAttribute.ConstructorArguments[0].Value.ToString();
|
|
var attributeMethod = handlerAttribute.ConstructorArguments[1].Value.ToString();
|
|
|
|
if (attributeModule == module && attributeMethod == method)
|
|
{
|
|
// Body param is optional so check for it
|
|
bool requiresXDocumentConstructor = handler.GetConstructors()
|
|
.Any(c => c.GetParameters().Any(p => p.ParameterType == typeof(XDocument)));
|
|
|
|
IHandler handlerInstance = requiresXDocumentConstructor
|
|
? (IHandler)ActivatorUtilities.CreateInstance(_serviceProvider, handler, body)
|
|
: (IHandler)ActivatorUtilities.CreateInstance(_serviceProvider, handler);
|
|
|
|
return await handlerInstance.HandleAsync(model);
|
|
}
|
|
}
|
|
|
|
//If no handler is found return an empty document
|
|
_logger.LogWarning($"No handler found for {model}/{module}/{method}");
|
|
|
|
return new XDocument();
|
|
}
|
|
}
|
|
}
|