[英]Is it ok to inject a record in the ASP.NET Core DI container?
Records make my code shorter.记录使我的代码更短。 For example, instead of
例如,而不是
public class OrderService
{
private readonly EcommerceContext _context;
public OrderService(EcommerceContext context)
{
_context = context;
}
}
I just have我只有
public record OrderService(EcommerceContext Context)
So, my question is, is it ok to inject a record in the DI container, or does it have any disadvantage?所以,我的问题是,在 DI 容器中注入一条记录是否可以,或者它有什么缺点吗?
A record is just a class with a auto-generated constructor;一条记录只是一个带有自动生成的构造函数的 class; The DI Container doesn't distinguish between the two of them.
DI 容器不区分它们两者。
Personally, I find record types a great way to remove the infrastructural code/cruft needed to practice DI and loose coupling.就我个人而言,我发现记录类型是一种消除实践 DI 和松散耦合所需的基础结构代码/垃圾的好方法。 Private fields, constructors, and private field assignments are just boilerplate code required to allow our code to be loosely coupled.
私有字段、构造函数和私有字段分配只是允许我们的代码松散耦合所需的样板代码。 Records allow reducing this code to the bare minimum, which is great.
记录允许将此代码减少到最低限度,这很棒。
The only downside that record types have is that, with the current version of C#, there's no way to guard incoming dependencies from being null
.记录类型的唯一缺点是,对于 C# 的当前版本,无法防止传入的依赖项成为
null
。 For me this isn't big of a deal in most cases, in which case I like to use record types.对我来说,在大多数情况下这没什么大不了的,在这种情况下我喜欢使用记录类型。 If null checks are mandatory (for instance because you are writing a reusable library, eg something you ship through NuGet), you need to fall back to old-school classes with manually implemented constructors.
如果 null 检查是强制性的(例如因为您正在编写一个可重用的库,例如您通过 NuGet 发送的东西),您需要回退到使用手动实现的构造函数的老式类。
When writing our book on DI , Mark Seemann and I actually discussed the use of record types as primary demonstration of constructor injection in our book.在撰写有关 DI 的书时,Mark Seemann 和我实际上讨论了使用记录类型作为我们书中构造函数注入的主要演示。 We, however, decided not to use record types in our book, mainly for three reasons:
然而,我们决定不在我们的书中使用记录类型,主要出于三个原因:
null
values into constructors.null
值注入构造函数。 Perhaps we'll change our mind in a (hypothetical) third edition of the book.也许我们会在本书的(假设的)第三版中改变主意。 This might especially happen when a future version of C# allows record type constructors to automatically check (and prevent) null arguments.
当 C# 的未来版本允许记录类型构造函数自动检查(并阻止)null arguments 时,尤其可能会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.