【问题标题】:.Net Core service using value from another service.Net Core 服务使用来自另一个服务的值
【发布时间】:2021-12-28 20:10:21
【问题描述】:

我目前正在尝试找到一种更好的方法来调用另一个类服务的构造函数中的服务函数。我对自己正在做的事情有一种不好的感觉,并认为我正在与 ASP .Net Core 的基础作斗争。我的问题是,我是否与.Net 方式作斗争?有没有更好的方法让我不创建 CryptionService 的新实例?

//this singleton has a function called GetSQLitePassword that returns a string
services.AddSingleton<ICryptionService, CryptionService>();

// Use value returned from cryptionService
services.AddScoped<ISQLiteSettingsRepo, 
    SQLiteSettingsRepo>(x => new SQLiteSettingsRepo(
        "./Settings.db", 
        new CryptionService().GetSQLitePassword()
    ));

我想我可以做这样的事情:

services.AddScoped<ISQLiteSettingsRepo, SQLiteSettingsRepo>(x => new SQLiteSettingsRepo(
    "./Settings.db", 
    service.GetService<ICryptionService>().GetSQLitePassword()
 ));

【问题讨论】:

    标签: c# .net service


    【解决方案1】:

    你为什么需要这个部件:x =&gt; new SQLiteSettingsRepo(...? 您应该在SQLiteSettingsRepo 的构造函数上注入ICryptionService 服务

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多