Property Injection in Asp.Net Core (转载)

问:


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; }

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?

 

答:


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. (意思就是.NET Core内置的DI包Microsoft.Extensions.DependencyInjection,现在不支持属性注入,只支持构造函数注入)


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.


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.


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.


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.


Avoid it everywhere else.

 

原文链接 

 

转载于:https://www.cnblogs.com/OpenCoder/p/9998864.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值