mickdelaney
6/10/2014 - 9:32 PM

EventUpconverter

..........snip.........

//Add EventUpconversion Mapping Profiles here, profiles must be loaded before running the upconverter finder
//Mapper.AddProfile<TypeOfProfile>();

var upconverterTypes = UpConversionFinder.GetUpconverters();
upconverterTypes.ForEach(x => builder.RegisterType(x));
    var wireup = Wireup.Init()
        .LogTo(x => new EventStoreLogger(LogManager.GetLogger(string.Format("EventStore.{0}", x.Name))))
        .UsingSynchronousDispatchScheduler(container.Resolve<IDispatchCommits>())
        .UsingSqlPersistence("EventStore")
        .WithDialect(new MsSqlDialect())
        .InitializeStorageEngine()
        .UsingNewtonsoftJsonSerialization(new VersionedEventSerializationBinder())
        .Compress()
        .UsingEventUpconversion();

    foreach (var upconverterType in upconverterTypes)
    {
        wireup.AddConverter((dynamic)container.Resolve(upconverterType));
    }

    var store = wireup.Build();
    
    
.........snip...........
public static class UpConversionFinder
    {
        public static List<Type> GetUpconverterTypes()
        {
            var eventVersionAttribute = typeof(VersionedEventAttribute);
            var eventBase = typeof(IEvent);
            var upconverterType = typeof (EventUpconverter<,>);

            return Mapper.GetAllTypeMaps()
                .Where(x => eventBase.IsAssignableFrom(x.SourceType) &&
                            eventBase.IsAssignableFrom(x.DestinationType) &&
                            x.SourceType.GetCustomAttributes(eventVersionAttribute, true).Any() &&
                            x.DestinationType.GetCustomAttributes(eventVersionAttribute, true).Any())
                .Select(mappedType => upconverterType.MakeGenericType(mappedType.SourceType, mappedType.DestinationType))
                .ToList();
        }
    }
public class EventUpconverter<TSource, TDestination> : IUpconvertEvents<TSource, TDestination>
        where TSource : class,IEvent
        where TDestination : class,IEvent
    {
        readonly IMappingEngine _mapper;

        public EventUpconverter(IMappingEngine mapper)
        {
            _mapper = mapper;
        }

        public TDestination Convert(TSource sourceEvent)
        {
            return _mapper.Map<TDestination>(sourceEvent);
        }
    }