Register和RegisterType之间的Autofac差异

Autofac difference between Register and RegisterType

我已经按照以下教程开始使用Autofac:
http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html

构造函数中没有参数的简单类

1
builder.RegisterType<ConsoleOutputService>().As<IOutputService>();

如本教程中所述,以上代码可以读取为:setup ConsoleOutputService作为IOutputService的实现。

构造函数中只有一个参数的简单类

1
builder.Register(c => new MultipleOutputService(outputFilePath)).As<IOutputService>();

我不明白为什么我们要使用lambda表达式来注册此类(以及该表达式的作用是什么)以及为什么我们不能键入此代码

1
builder.RegisterType<MultipleOutputService(outputFilePath)>().As<IOutputService>();

在此先感谢您的帮助


您无法编写该代码,因为它在C#中没有意义。
RegisterType是通用方法; 通用方法必须将类型作为通用参数。

您正在尝试使用自定义方式注册类型以创建类型(在这种情况下,应使用构造函数参数); C#支持指定这种事情的唯一方法是lambda表达式(或其他委托)。


顺便说一句,对此Autofac来说,有一个更好的解决方案,在其注册生成器中引入了.WithParameter()扩展名。

1
.RegisterType<MultipleOutputService>().As<IOutputService>().WithParameter("parameterName","parameterValue");

这应该满足您需要将接口类型以外的其他内容传递给构造函数之一的事件


lambda变体使我们能够在构造实例时执行一些逻辑。