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

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

问题描述

我有一个点网核心项目,我想在我的Controller 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

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

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

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