用于Web API,管理面板和MVC控制器的依赖项注入的通用代码 [英] Common code for dependency injection for web api, admin panel and mvc controller

查看:84
本文介绍了用于Web API,管理面板和MVC控制器的依赖项注入的通用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我的解决方案文件中包含以下4个项目:

Currently, I have below 4 projects in my solution file :

  1. API(Web API)
  2. Web(MVC)
  3. 管理员(MVC)
  4. 服务层(C#库)

这3个Web项目都正在使用服务层. 该服务是使用Autofac容器注入的.

The service layer is being used by all the 3 web projects. The service is injected using Autofac container.

服务在启动期间在每个Web项目中注册,这导致代码重复.有没有一种更简单的方法可以在一个地方注册所有依赖项,以便所有项目都可以重用它?

The services are registered in each of the web projects during startup which is causing duplication of the code. Is there a simpler way where I can register all the dependencies in one place so that it can be reused by all the projects?

我们非常感谢您的帮助.

Any help is highly appreciated.

推荐答案

您可以尝试的另一种方法

One more approach you can try

  • 添加一个常见文件,例如 AutofacBootstrap ,公开一个静态方法, 除Autofac容器外,此方法应注册所有常用的 类.您可以在单独的公共项目中拥有此文件.

  • Add a common file like AutofacBootstrap, expose a static method which excepts Autofac Container, this method should register all your common classes. You can have this file in a separate common project.

包括该类作为指向其他项目的链接.为了这 右键单击项目,选择添加>现有项目,然后在 对话框中,点击添加按钮,然后选择添加为链接.

Include that class as a link to other projects. For this Right-click the project, select Add > Existing Item, and in the dialog drop down the Add button and select Add As Link.

现在您有了一个通用文件,该文件具有指向所有项目的链接.

Now you have a common file which have a link to all the projects.

接下来,在启动单个项目时,通过以下方式调用通用方法: 通过容器.另外,引导您的本地依赖项.

Next is, in startup of individual project, call the common method by passing the container. In addition bootstrap your local dependencies.

我希望这会有所帮助.

这篇关于用于Web API,管理面板和MVC控制器的依赖项注入的通用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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