Autofac:替代实现但注入旧实现?

Autofac: Substitute implementation but inject old implementation?

我正在编写事件源应用程序。我有一个由 EventStore class 实现的 IEventStore。但是,在调试时,我想将 IEventStore 实现为 DebuggingEventStore class.

我能否以某种方式在 DebuggingEventStore 的构造函数中注入我的 EventStore(旧实现)?我看过装饰器,但我不确定在这种情况下它是否是正确的方法。

之前

IEventStore 实现为 EventStore

现在

IEventStore在调试时实现为DebuggingEventStore

我想要的

DebuggingEventStore 通过其构造函数注入旧的 IEventStoreEventStore)。

您可以实现 DebuggingEventStore 以在构建 iOS 容器时注入其构造函数中的 EventStore。

实际上,DebuggingEventStore 将实现 IEventStore 并将 EventStore 作为构造函数参数。

void Main()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<EventStore>().AsSelf();
    builder.Register(cc => new DebugingEventStore(cc.Resolve<EventStore>())).As<IEventStore>();
    var container = builder.Build();

    container.Resolve<IEventStore>().DoWork();

}

public interface IEventStore
{
    void DoWork();
}

public class EventStore : IEventStore
{
    public EventStore(Foo doo, Bar bar)
   { ....} 
    void IEventStore.DoWork()
    {
        Console.WriteLine("EventStore");
    }
}

public class DebuggingEventStore: IEventStore
{
    private IEventStore _internalEventStore;

    public DebuggingEventStore(IEventStore eventStore)
    {
        this._internalEventStore = eventStore;
    }
    void IEventStore.DoWork()
    {
        this._internalEventStore.DoWork();
        Console.WriteLine("DebuggingEventStore");
    }
}

正如 Nicholas Blumhardt 所述here,在 Autofac 中注册(非通用)装饰器的典型方法如下:

builder.RegisterType<EventStore>()
    .Named<IEventStore>("implementor");

builder.RegisterDecorator<IEventStore>(
    (c, decoratee) => new DebuggingEventStore(decoratee),
    fromKey: "implementor");

但话虽如此,我认为@KnightFox 的回答在注册非通用装饰器时更清晰:

builder.RegisterType<EventStore>().AsSelf();
builder.Register(c => new DebugingEventStore(c.Resolve<EventStore>()))
    .As<IEventStore>();