-
Notifications
You must be signed in to change notification settings - Fork 3
Description
Hi
It would be nice if it was possible to customize the mapping. For example be able to map based on a convention saying that the eventhandler must start with subject from event.
If you refactor the EventGridOptions to take a mapper, then one can extend the maping with own requirements
//Default mapper
`public class EventGridMapper
{
private readonly Dictionary<string, Type> handlers = new Dictionary<string, Type>();
public virtual void AddMapping(string eventType, Type type)
{
handlers.Add(eventType.ToLower(), type);
}
public virtual Type LookUp(Event item)
{
var resulttype = handlers.FirstOrDefault(i => i.Key == item.EventType.ToLower());
return resulttype.Equals(default(KeyValuePair<string, Type>)) ? null : resulttype.Value;
}
}
`
//Mapper that will map to handlers starting with subject, fx. {Subject}_SomeEventHandler public class SubjectEventGridMapper : EventGridMapper
{
private readonly Dictionary<string, List> handlers = new Dictionary<string, List>();
public override void AddMapping(string eventType, Type type)
{
if (handlers.Any(h => h.Key == eventType.ToLower()))
handlers[eventType].Add(type);
else
handlers.Add(eventType.ToLower(), new List<Type> { type });
}
public override Type LookUp(Event item)
{
var key = item.EventType.ToLower();
if (handlers.ContainsKey(key) && handlers[key].Any(t => t.Name.StartsWith(item.Subject + "_")))
return handlers[key].First(t => t.Name.StartsWith(item.Subject + "_"));
return null;
}
}
``using System;
using SharpEventGrid;
namespace SharpEventGridServer
{
public class EventGridOptions
{
protected Type _defaultMapping;
internal IServiceProvider ServiceProvider { get; set; }
public string EventsPath { get; set; } = "api/events";
public bool AutoValidateSubscription { get; set; } = true;
public Action ValidateSubscriptionCallBack { get; set; }
public string ValidationKey { get; set; }
public string ValidationValue { get; set; }
public Action<string, bool, string> AutoValidateSubscriptionAttemptNotifier { get; set; }
public EventGridMapper Mapper = new EventGridMapper();
public virtual void MapEvent<T>(string eventType) where T : IEventGridHandler
{
Mapper.AddMapping(eventType, typeof(T));
}
public void MapDefault<T>() where T : IEventGridHandler
{
_defaultMapping = typeof(T);
}
public void SetValidationKey(string key, string value)
{
ValidationKey = key;
ValidationValue = value;
}
internal virtual IEventGridHandler ResolveHandler(Event item)
{
var typeToCreate = Mapper.LookUp(item);
if (typeToCreate == null)
typeToCreate = _defaultMapping;
var handler = ServiceProvider.GetService(typeToCreate) ?? Activator.CreateInstance(typeToCreate);
return (IEventGridHandler)handler;
}
}
}``