.net核心webapi应用程序与entityframeworkcore。 除了dbcontext之外,还试图弄清楚如何将其他连接字符串传递到数据访问库类中。请参阅** dbcontext **以下是我想要做的。
startup.cs
var SqlConnection = Configuration.GetConnectionString("SQLConnection");
var BlobConnection = Configuration.GetConnectionString("BlobConnection");
services.AddEntityFramework()
.AddEntityFrameworkSqlServer()
.AddDbContext<VISTrackingContext>(options => options.UseSqlServer(SqlConnection,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(5),
errorNumbersToAdd: null);
}));
services.AddScoped<IDataManager>(c => new DataManager(**_dbcontext**, BlobConnection));
public FileController(IDataManager manager)
{
_datamanager = manager;
}
public DataManager(VISTrackingContext dbcontext, string blobconnection)
{
_dbcontext = dbcontext;
_blobconnection = blobconnectionstring;
}
可以这样做吗?或者是否有另一种方法通过上下文对象本身注入一个额外的连接字符串?我在这方面看到了很多评论和选项,但没有一种方法处理上下文和传递给存储库对象的连接字符串。
答案 0 :(得分:0)
您可以将这些连接字符串存储在对象中,并将其注入DataManager。
例如,
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton(provider => new DataSettings(
Configuration.GetConnectionString("SQLConnection"),
Configuration.GetConnectionString("BlobConnection")));
services.AddScoped<IDataManager, DataManager>();
...
}
}
public class DataSettings
{
public DataSettings(string sqlConnection, string blobConnection)
{
SQLConnection = sqlConnection;
BlobConnection = blobConnection;
}
public string SQLConnection { get; }
public string BlobConnection { get; }
}
public DataManager(VISTrackingContext dbcontext, DataSettings dataSettings)
{
_dbcontext = dbcontext;
_blobconnection = dataSettings.BlobConnection;
}
答案 1 :(得分:0)
除了@Win的答案,更通用的方法:
public class ConnectionStrings : Dictionary<string,string> { }
Startup.cs
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
service.AddScoped<IDataManager,DataManager>();
// or
services.AddScoped<IDataManager>(c => new DataManager(
c.GetRequiredService<YourDbContext>(),
c.GetRequiredService<ConnectionStrings>()["BlobConnection"])
);
服务
public DataManager(VISTrackingContext dbcontext, ConnectionStrings connectionStrings)