net core 2.1 依赖注入 [英] net core 2.1 Dependency injection

查看:37
本文介绍了net core 2.1 依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dot net core 项目,我想在我的控制器中注入 IContextDb

I have dot net core project , I want to inject in my Controller IContextDb

我有很多类继承自 IContextDb即 (ShopContext, UserContext, ..) : IContextDb

I have many class inherit from IContextDb ie (ShopContext, UserContext, ..) : IContextDb

我的问题是:

1 - 有没有办法在正确的控制器中注入正确的上下文在我的控制器中实时注入上下文

1 - Is there way to inject the right context in the right Controller to inject the context in my controller in real time

我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddTransient<IContextDb>(
    serviceProvider => 
      {
         /// to do to map IContextDb with right context for
         /// right controller 
         /// or using reflection  
       });
    services.AddOptions();
    services.AddMvc();
  }

我的 MVC 控制器:

public class UserController
{
    private IContextDb _userContext
    public UserController(IContextDb userContext)
    {
       _userContext = userContext;
    }
}

推荐答案

只需在每个控制器中注入具体的类

Just inject the concrete class in each controller

public class UserController
{
    private IContextDb _userContext
    public UserController(UserContext userContext)
    {
       _userContext = userContext;
    }
}

这篇关于net core 2.1 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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