【问题标题】:IdentityServer4 - Inject ConfigurationDbContext for use in classIdentityServer4 - 注入 ConfigurationDbContext 以在类中使用
【发布时间】:2017-05-23 07:59:53
【问题描述】:

我在ConfigurationDbContext 中保留配置。我现在正在创建一个 ServiceProvider,它允许以后动态添加 Clients、ApiResources 等。

我的问题是,在课堂上检索 ConfigurationDbContext 的最佳方法是什么?如果依赖注入是最佳答案,我如何将ConfigurationDbContext 注册为服务,以及如何从Startup.cs 之外的类中检索该服务,而IApplicationBuilder.ApplicationServices 不可用?

【问题讨论】:

标签: c# asp.net-core identityserver4


【解决方案1】:

这是定义 ConfigurationDbContext 后的操作方法。

  1. 在Startup.cs文件中注册ConfigurationDbContext如下。

    public void ConfigureServices(IServiceCollection services)
    {
       string connectionString = "my connection string";
    
       services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ConfigurationDbContext>(options => 
                options.UseSqlServer(connectionString));
    
        //Add more services here e.g.
        services.AddMvc();
    }
    
  2. 在需要的地方使用 ConfigurationDbContext。

    public class MyClassWhereDbContextIsNeeded
    {
       private readonly ConfigurationDbContext dbContext;
    
       //Inject context instance here.
       public MyClassWhereDbContextIsNeeded(ConfigurationDbContext dbContext)
       {
          this.dbContext = dbContext;
       }
    
       public void SomeMethod()
       {
          //Use DbContext here e.g. Get customers from database.
          var customers =  dbContext.Customers.ToList());
       }
     }
    

【讨论】:

  • 但是当/如果我需要创建 MyClassWhereDbContextIsNeeded 的实例时,我是否还需要提供实例?另外,理想情况下,我想在该类的方法中创建一个新的 Dbcontext 实例,这样我就可以做一个工作单元并处理它
  • 理想情况下,您会将 MyClassWhereDbContextIsNeeded 注册为依赖项之一,并在需要 MyClassWhereDbContextIsNeeded 实例的地方注入它。依赖注入的整个想法是通过注入依赖而不是在代码中显式创建实例来减少紧密耦合。您的 DI 容器将根据您注册依赖项的方式来创建/销毁实例。
  • 感谢您的回复。我的困惑是我有一个名为RoleService 的类,它有“AddRole”、“DeleteRole”等方法。我希望这些方法中的每一个都能在它们的主体中检索一个 DbContext。
猜你喜欢
  • 2018-01-16
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
相关资源
最近更新 更多