加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 将存储库注入ASP.NET控制器的最佳方法是什么

发布时间:2020-12-16 07:00:50 所属栏目:asp.Net 来源:网络整理
导读:我们有一个用ASP.NET MVC编写的项目,我们使用NInject将存储库注入控制器.目前我们正在使用属性和Inject-attribute来注入存储库,这很好用: [Inject]public IMyRepository MyRepos {get;set;} 另一种注入方法是使用NInjectServiceLocator“手动”执行: var m
我们有一个用ASP.NET MVC编写的项目,我们使用NInject将存储库注入控制器.目前我们正在使用属性和Inject-attribute来注入存储库,这很好用:

[Inject]
public IMyRepository MyRepos {get;set;}

另一种注入方法是使用NInjectServiceLocator“手动”执行:

var myRepos = NInjectServiceLocatorInstance.Resolve<IMyRepository>();

现在我想知道以下内容:第一种方法要求所有存储库都列在控制器的顶部(当然不一定在顶部,但它是最合理的位置).每当发出请求时,NInject都会实例化每个存储库.无论是否在特定Action内实际需要所有存储库,都会发生这种情况.

使用第二种方法,您可以更精确地控制实际需要哪些存储库,因此在创建控制器时可能会节省一些开销.但是您可能还必须包含代码以在多个位置检索相同的存储库.

那么哪一个会更好?是否拥有一堆存储库属性更好还是更好地解决在您需要的时间和地点实际需要特定操作的存储库?注入“无用”存储库是否会导致性能下降?那里有(甚至;-)更好的解决方案吗?

解决方法

使用DI时,构造函数注入应该是您的默认选择.

你应该问问自己,控制器是否真的依赖于那个特定的类来工作.

如果只有特定的方法需要依赖,那么方法注入也可以是特定场景的解决方案.

我从未使用过Property Injection,但Mark Seeman在他的书(Dependency Injection in .NET)中描述了它:

PROPERTY INJECTION should only be used when the class you’re developing has a good
LOCAL DEFAULT and you still want to enable callers to provide different implementations
of the class’s DEPENDENCY.

PROPERTY INJECTION is best used when the DEPENDENCY is optional.

NOTE There’s some controversy around the issue of whether PROPERTY INJECTION
indicates an optional DEPENDENCY. As a general API design principle,I
consider properties to be optional because you can easily forget to assign
them and the compiler doesn’t complain. If you accept this principle in the
general case,you must also accept it in the special case of DI. 4

本地默认值描述为:

A default implementation of an ABSTRACTION that’s defined in the same assembly as
the consumer.

除非您正在构建API,否则我建议不要使用Property Injection

Whenever a request is made,NInject instantiates each and every repository. This happens regardless of whether all of the repositories are actually needed inside a specific Action.

在使用构造函数注入时,我认为您不应该担心性能

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读