Skip to content

Hooking up your IoC container

Tomas Lycken edited this page Oct 30, 2017 · 3 revisions

Hooking up your IoC container will of course look different depending on both which container you use, and which storage backend you use. Here's an example using Autofac and EF6, taken from the sample project:

public class EventSourcingModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterAssemblyTypes(typeof(IEventStream<,,>).GetTypeInfo().Assembly)
            .AsImplementedInterfaces()
            .SingleInstance();

        builder
            .RegisterInstance(new TranslatingEventRegistry(
                new Dictionary<string, string>
                {
                    // If events are renamed (e.g. if switching from SimpleEventRegistry to AssemblyEventRegistry)
                    // add translations here. Example:
                    { "OldEventName", "NewEventName" }
                },
                new AssemblyEventRegistry(typeof(MessagePostedEvent), type => type.Name.EndsWith("Event"))))
            .AsImplementedInterfaces()
            .SingleInstance();

        builder
            .RegisterType<EntityFrameworkEventStore<long, string, EventsContext, ApplicationEvent, IEventMetadata<string>, PersistenceEvent>>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

        builder
            .RegisterType<EventsContext>()
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

        builder
            .RegisterType<DefaultEventSerializer<string, ApplicationEvent, PersistenceEvent>>()
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

        builder
            .RegisterType<DefaultEventFactory<string, ApplicationEvent>>()
            .AsImplementedInterfaces()
            .SingleInstance();

        builder
            .RegisterType<WriteLock<string>>()
            .AsSelf()
            .AsImplementedInterfaces()
            .SingleInstance();

        base.Load(builder);
    }
}