我有一个使用存储库模式制作的 asp net core web api 应用程序。当请求到达我的控制器时,我调用一个服务依赖方法,然后在刚刚调用的该服务中,我调用另一个服务,这只是我的存储库层。存储库层中的此类
MyRepo.cs
依赖于我制作的DBContext.cs
类。
// 应用程序设置.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Database": {
"ConnectionString": connection string"
}
}
// 程序.cs
// APPSETTIGS CONFIG
builder.services.Configure<DatabaseConfig>(
config.GetSection(DatabaseConfig.ConfigSectionName)); //Appsetting `Database` property
builder.services.AddScoped<IMyService, MyService>();
builder.services.AddScoped<IMyRepo, MyRepo>();
// MyService.cs
public class MyService: IMyService
{
private IMyRepo _myRepo;
public SurveyFormDataServices(IMyRepo myRepo)
{
_myRepo= myRepo;
}
public IEnumerable<MyTypes> GetTypes()
{
var types= _myRepo.GetTypes();
...
}
}
// MyRepo.cs
public class MyRepo: IMyRepo
{
private SqlConnection sqlConnection;
public IEnumerable<MyType> GetTypes()
{
using (sqlConnection = DBContext.GetConnection())
{
...
}
}
}
// DBContext.cs
public sealed class DBContext
{
private readonly DatabaseConfig _options;
private static string connectionString = string.Empty;
public DBContext(IOptions<DatabaseConfig> options)
{
_options = options.Value;
connectionString = _options.ConnectionString;
}
public static SqlConnection GetConnection()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
}
正如您在我的
DBContext.cs
类中看到的,构造函数有一个来自注入的 AppSettings 的参数 IOptions
。我通过将选项模式绑定到表示设置的类来完成选项模式。
我的问题是,在
MyRepo.cs
中,如果我这样做:
using (sqlConnection = DBContext.GetConnection())
我的
connectionString
文件中的 DBContext.cs
属性将为空,因为我猜测我没有使用 new DBContext(IOptions)
进行实例化。我想避免这种情况,即使我这样做,我也会收到错误,因为我不知道如何传入IOptions
,而且我宁愿不这样做。
如何调用或使用 DBContext.GetConnection()
函数并确保 GetConnection()
将具有 appsettings.json中的
connectionString
值
正确的方法是修改你的
MyRepo
类并在那里使用DI。
public class MyRepo : IMyRepo
{
private DBContext context;
public MyRepo(DbContext ctx) => context = ctx;
public IEnumerable<MyType> GetTypes()
{
using (sqlConnection = context.GetConnection())
{
...
}
}
}
并使
GetConnection()
成为实例方法。
您还应该将您的
DbContext
类重命名为其他名称,因为实体框架也有一个同名的类,任何阅读您代码的人都会对您的即席语义感到困惑。