AutoFac 注册混乱

AutoFac Register confusion

您好,我刚刚在查看 AutoFac 并遵循他们的入门教程

http://autofac.readthedocs.org/en/latest/getting-started/index.html

遵循它并了解他们的服务如何工作后,我想尝试在相同的接口类型上创建一个新的实现

builder.RegisterType<TodayWriter>().As<IDateWriter>();
builder.RegisterType<TomorrowWriter>().As<IDateWriter>();

两个实现包含相同的代码

public class TomorrowWriter : IDateWriter
{
    private IOutput _output;

    public TomorrowWriter(IOutput output)
    {
        this._output = output;
    }

    public void WriteDate()
    {
        this._output.Write(DateTime.Today.AddDays(1).ToShortDateString());
    }
}

所以TodaysWriter除了显示的WriteDate方法是一样的

this._output.Write(DateTime.Today.ToShortDateString());

相反。

现在使用该应用程序,我该如何确定要使用的实现,因为这两种方法都被称为 WriteDate()

        using(var scope = Container.BeginLifetimeScope())
        {
            var writer = scope.Resolve<IDateWriter>();

            // Is this using todaysWriter or TomorrowWriter?
            writer.WriteDate();
        }

我是不是用错了?

谢谢

要区分同一接口的不同实现,请查看文档中的 named and keyed services

或者,您可以通过注册 DateWriterFactory 并在其上使用一种方法来获得特定的 IDateWriter 实现,从而推出自己的产品。类似于:

public class DateWriterFactory
{
    IDateWriter GetWriter(string writerName)
    {
        if (writername=="TodayWriter")
            return new TodayWriter();
        if (writername=="TomorrowWriter")
            return new TomorrowWriter();
    }
}

显然,工厂的实现可以根据您的需要复杂或简单。或者您可以只使用获取固定编写器的方法,而不是传入字符串。