Pass multiple connection strings through IServicesCollection.AddScoped()

app-startup asp.net-core dbcontext entity-framework-core

Question

.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.

1
0
6/28/2017 3:49:18 PM

Popular Answer

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)
0
6/28/2017 6:09:44 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow