如何使用Autofac注册通用操作?

时间:2015-10-27 00:28:09

标签: c# dependency-injection autofac

[在评论者要求中编辑了更多详情]

如果我有以下内容:

myClassInstance.Register<MyCommand>(new MyCommandHandler().Handle);

我可以轻松地在不同的处理程序中重复上面的行。

但是,我想知道有没有办法使用Autofac通过惯例一般注册它们?

以下是反映现有非DI代码的代码:

public static class Program
{
    public static void Main()
    {
        IMockBus bus = new MockBus();

        var eventStore = new EventStore(bus);
        var repository = new Repository<InventoryItem>(eventStore);

        // Command
        bus.RegisterHandler<CreateItem>(
            new CreateItemCommandHandler(repository).Handle);

        // Event
        bus.RegisterHandler<ItemCreated>(
            new ItemCreatedEventHandler().Handle);
    }
}

public interface IMockBus
{
    void RegisterHandler<T>(Action<T> handler) where T : IMessage;
}

public interface ISendCommands
{
    void Send<T>(T command) where T : Command;
}

public abstract class Command : IMessage
{
}

public interface IMessage
{
}

public interface IPublishEvents
{
    void Publish<T>(T @event) where T : Event;
}

public class Event : IMessage
{
    public int Version;
}

public class MockBus : IMockBus
{
    private readonly Dictionary<Type, List<Action<IMessage>>> routes = 
        new Dictionary<Type, List<Action<IMessage>>>();

    public void RegisterHandler<T>(Action<T> handler) where T : IMessage
    {
        List<Action<IMessage>> handlers;

        if (!routes.TryGetValue(typeof(T), out handlers))
        {
            handlers = new List<Action<IMessage>>();

            routes.Add(typeof(T), handlers);
        }

        handlers.Add((message => handler((T)message)));
    }
}

0 个答案:

没有答案