代码之家  ›  专栏  ›  技术社区  ›  Ela Buwa

将ApplicationDBContext注入非控制器文件

  •  0
  • Ela Buwa  · 技术社区  · 2 年前

    我正试着注射 ApplicationDBContext 进入一个服务或非控制器文件,并被DI卡住了一点。

    Program.cs 摘录

    builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
    
    builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(
            builder.Configuration.GetConnectionString("DefaultConnection")
        ));
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();
    
    builder.Services.AddDistributedMemoryCache();
    
    builder.Services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
    
    builder.Services.AddScoped<IAppSettingsService, AppSettingsService>();
    
    var app = builder.Build();
    

    服务/非控制器文件:

    using NVFlexo.Data;
    
    namespace NVFlexo.Services;
    
    public interface IAppSettingsService
    {
        public string GetSetting(string key);
    }
    
    public class AppSettingsService: IAppSettingsService
    {
        private readonly ApplicationDbContext _db;
    
        public AppSettingsService(ApplicationDbContext db)
        {
            _db = db;
        }
        
        public string GetSetting(string key)
        {
            var results = _db.AppSettings.Where(s => s.SettingKey == key).First();
            if (results == null)
            {
                return null;    
            }
            return results.Value;
        }
    }
    

    我正在尝试访问的一个方法 AppSettingsService 类,如另一个文件中所示:

    AppSettingsService appSettingsService = new AppSettingsService();
    appSettingsService.GetSetting("GST");
    

    我收到以下错误:

    构造函数“AppSettingsService”有1个参数,但使用0个参数调用

    这很有道理。但是,有没有办法在不注入的情况下自动加载数据库连接?

    我想我来自PHP/Laravel背景,在那里数据库连接是自动处理的,似乎需要显式地添加数据库上下文。NET核心?

    如果有人能给我指明正确的方向,我将不胜感激。

    谢谢你抽出时间。

    编辑 我正试图从下面的控制器方法中使用这个。

    public IActionResult GetItem(string? key)
    {
       // AppSettingsService appSettingsService = new AppSettingsService();
          AppSettingsService appSettingsService = new AppSettingsService(_db);  //This works
        appSettingsService.GetSetting(key);
    
        return this.StatusCode(StatusCodes.Status200OK, "Retrieved");
    }
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   ProgrammingLlama Raveena Sarda    2 年前

    您需要使用依赖项注入来获得 IAppSettingsService 。你不能只使用 new 要创建一个新的容器,因为它不使用容器来获取依赖项——您必须手动传递它们。

    通常,您会像这样将其注入(到控制器、其他服务等中):

    public class MyController
    {
        private readonly IAppSettingsService _appSettingsService;
    
        public MyController(IAppSettingsService appSettingsService)
        {
            _appSettingsService = appSettingsService;
        }
    
        public IActionResult GetItem(string? key)
        {
            _appSettingsService.GetSetting(key);
            return this.StatusCode(StatusCodes.Status200OK, "Retrieved");
        }
    }
    

    在ASP。NET核心控制器,您也可以使用 [FromServices] 将服务注入控制器动作方法:

    public IActionResult GetItem(string? key, [FromServices] IAppSettingsService appSettingsService)
    {
        appSettingsService.GetSetting(key);
        return this.StatusCode(StatusCodes.Status200OK, "Retrieved");
    } 
    

    注意,我们正在注射 IAppSettingsService 在这里,而不是 AppSettingsService 。这是因为您已将服务注册为 IAppSettingsService ,而DI容器不知道什么 应用程序设置服务