简体   繁体   English

WebAPI的依赖注入

[英]Dependency Injection with WebAPI

Scenario: 场景:

I created one solution with 2 projects. 我用2个项目创建了一个解决方案。 One is Web API project and another is class library for repositories. 一个是Web API项目,另一个是存储库的类库。

I added ninject as DI into WebAPI project. 我将ninject作为DI添加到WebAPI项目中。 This blog well defined to use ninject with WebAPI. 这个博客很好地定义为使用ninject和WebAPI。

I can configure repository Classes in RegisterServices methods in NinjectWebCommon.cs file. 我可以在NinjectWebCommon.cs文件中的RegisterServices方法中配置存储库类。 This is available in app_start folder of Web api project. 这可以在Web api项目的app_start文件夹中找到。

Clarification: 澄清:

I am confused that, now again i added reference of repository project to web api project to register dependency classes. 我很困惑,现在我再次将web项目的引用添加到web api项目以注册依赖项类。 Then how it is not seperate from repository project. 那么它是如何不与存储库项目分开的。

Questions: 问题:

Is this the correct way or i missed anything? 这是正确的方式还是我错过了什么?

May i misunderstood the concept ? 我可能误解了这个概念吗? May be reflection to check runtime class find can avoid dependency 可能是反映检查运行时类查找可以避免依赖

Please advise and give any correct blog or sample to explain this 请建议并提供任何正确的博客或样本来解释这一点

You're missing the 3rd project which is your bridge between your WebAPI and Repository library. 你错过了第三个项目,它是你的WebAPI和Repository库之间的桥梁。 Usually it contains your interfaces that your plugin DLL objects would implement and your WebAPI would use. 通常它包含插件DLL对象将实现的接口以及WebAPI将使用的接口。 All of your WebAPI code should be using interfaces as it is the job of DI to give you the correct class based on the configuration. 您的所有WebAPI代码都应该使用接口,因为DI的工作是根据配置为您提供正确的类。

This is what allows you to swap out DLLs, add DLLs for new options, etc. The WebAPI project shouldn't reference the plugin because, well, you made a dependency on something you are trying to make dynamic. 这是允许您交换DLL,为新选项添加​​DLL等的原因.WebAPI项目不应该引用该插件,因为,您依赖于您尝试动态的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM