Asp.Net Core中的属性注入 [英] Property Injection in Asp.Net Core

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

问题描述

我正在尝试将asp.net应用程序移植到asp.net核心.我在这样的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核心上的内置DI实现相同的功能?还可以使用基于约定的绑定吗?

Is there a way to achieve the same functionality using build 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.

通过构造函数注入,您可以通过构造函数强制执行此操作,并检查null和not创建类的实例.使用属性注入,这是不可能的,并且在单元测试期间,当在构造函数中未定义类时,类所需的服务/依赖关系并不明显,因此很容易错过并获得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中的属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆