我正在尝试将
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 Core 中显式添加数据库上下文?
如果有人能指出我正确的方向,请感激不已。
感谢您的宝贵时间。
-- 编辑 我正在尝试从控制器方法中使用它,如下所示。
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");
}
需要使用依赖注入来获取
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 Core 控制器中,您还可以使用
[FromServices]
将服务注入到控制器操作方法中:
public IActionResult GetItem(string? key, [FromServices] IAppSettingsService appSettingsService)
{
appSettingsService.GetSetting(key);
return this.StatusCode(StatusCodes.Status200OK, "Retrieved");
}
请注意,我们在这里注入
IAppSettingsService
,而不是 AppSettingsService
。这是因为您已将服务注册为 IAppSettingsService
,而 DI 容器不知道 AppSettingsService
是什么。