Register和RegisterType之间的Autofac差异 [英] Autofac difference between Register and RegisterType
问题描述
我已按照以下教程开始使用Autofac: http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html
I have started to use Autofac following this tutorials: http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html
构造函数中没有参数的简单类
builder.RegisterType<ConsoleOutputService>().As<IOutputService>();
如本教程中所述,上面的代码可以读取为:将ConsoleOutputService设置为IOutputService的实现
As explained in the tutorial, the code above can be read as: setup ConsoleOutputService as the implementation of IOutputService
在构造函数中具有一个参数的简单类
builder.Register(c => new MultipleOutputService(outputFilePath)).As<IOutputService>();
我不明白为什么我们要使用lambda表达式来注册此类(以及该表达式的作用是什么)以及为什么我们不能键入此代码
I don't understand why are we using a lambda expression to register this class (and what does this expression exactly does) and why we can't type this code
builder.RegisterType<MultipleOutputService(outputFilePath)>().As<IOutputService>();
预先感谢您的帮助
推荐答案
您无法编写该代码,因为它在C#中没有意义.
RegisterType
是通用方法;通用方法必须采用 types 作为通用参数.
You can't write that code because it doesn't make sense in C#.
RegisterType
is a generic method; generic methods must take types as generic parameters.
您正在尝试使用自定义方式注册类型以创建它(在您的情况下为构造函数参数); C#支持指定这种事情的唯一方法是lambda表达式(或其他委托).
You're trying to register a type with a custom way to create it (inyour case, a constructor parameter); the only way that C# supports to specify such a thing is a lambda expression (or other delegate).
这篇关于Register和RegisterType之间的Autofac差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!