gpt4 book ai didi

Autofac Register 和 RegisterType 的区别

转载 作者:行者123 更新时间:2023-12-01 16:19:07 25 4
gpt4 key购买 nike

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

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

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

正如教程中所解释的,上面的代码可以理解为:将 ConsoleOutputService 设置为 IOutputService 的实现

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

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

我不明白为什么我们使用 lambda 表达式来注册此类(以及这个表达式到底做什么)以及为什么我们无法键入此代码

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

预先感谢您的帮助

最佳答案

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

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

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

关于Autofac Register 和 RegisterType 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7984426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com