.net core webapi application with entityframeworkcore. Trying to figure out how to pass an additional connection string into the data access library class in addition to the dbcontext. See ** dbcontext ** below is what I want to do.
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;
}
Can this be done? Or is there another way to inject an additional connection string through the context object itself? I see lots of comments and options on doing this but none of the approaches deal with both the context and the connection string being passed to the repository object.
Alternatively to @Win's answer, a more generic approach:
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"])
);
Service
public DataManager(VISTrackingContext dbcontext, ConnectionStrings connectionStrings)