本文介绍了ASP.NET Core 中的属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ASP.NET 应用程序移植到 ASP.NET Core.我的 UnitOfWork 实现上有属性注入(使用 Ninject),如下所示:

I am trying to port an ASP.NET application to ASP.NET Core. I have property injection (using Ninject) on my UnitOfWork implementation like this:

[Inject]
public IOrderRepository OrderRepository { get; set; }
[Inject]
public ICustomerRepository CustomerRepository { get; set; }

有没有办法在 .NET Core 上使用内置 DI 来实现相同的功能?另外,是否可以使用基于约定的绑定?

Is there a way to achieve the same functionality using built-in DI on .NET Core? Also, is it possible to use convention-based binding?

推荐答案

不,内置的 DI/IoC 容器在使用和功能方面都特意保持简单,以便为其他 DI 容器插入插件提供基础.

No, the built-in DI/IoC container is intentionally kept simple in both usage and features to offer a base for other DI containers to plug-in.

因此没有内置支持:自动发现、自动注册、装饰器或注入器,或基于约定的注册.据我所知,目前也没有计划将其添加到内置容器中.

So there is no built-in support for: Auto-Discovery, Auto-Registrations, Decorators or Injectors, or convention based registrations. There are also no plans to add this to the built-in container yet as far as I know.

您必须使用支持属性注入的第三方容器.

You'll have to use a third party container with property injection support.

请注意,属性注入在 98% 的场景中都被认为是不好的,因为它隐藏了依赖关系,并且不能保证在创建类时对象会被注入.

Please note that property injection is considered bad in 98% of all scenarios, because it hides dependencies and there is no guarantee that the object will be injected when the class is created.

使用构造函数注入,您可以通过构造函数强制执行此操作,并检查是否为空,而不是创建类的实例.使用属性注入这是不可能的,并且在单元测试期间,当它们没有在构造函数中定义时,类需要哪些服务/依赖项并不明显,因此很容易错过并获得 NullReferenceExceptions.

With constructor injection you can enforce this via constructor and check for null and the not create the instance of the class. With property injection this is impossible and during unit tests its not obvious which services/dependencies the class requires when they are not defined in the constructor, so easy to miss and get NullReferenceExceptions.

我发现的属性注入的唯一有效原因是将服务注入到由第三方库生成的代理类中,即从接口创建的 WCF 代理,您无法控制对象的创建.即使在那里,它也仅适用于第三方库.如果您自己生成 WCF 代理,则可以通过 partial class 轻松扩展代理类,并添加新的 DI 友好构造函数、方法或属性.

The only valid reason for Property Injection I ever found was to inject services into proxy classes generated by a third party library, i.e. WCF proxies created from an interface where you have no control about the object creation. And even there, its only for third party libraries. If you generate WCF Proxies yourself, you can easily extend the proxy class via partial class and add a new DI friendly constructor, methods or properties.

避免在任何地方其他地方.

这篇关于ASP.NET Core 中的属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:35