Steven Mayer
Steven Mayer

Reputation: 661

ASP.NET 5 DI Connection String into ADO.NET

Good morning,

We are currently migrating away from EF to using ADO.NET for our backend. For EF, it was very easy to inject the connection string. However, I am unable to figure out how to do it with a standard service. Code currently is:

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>();

Currently going through the Dependency Injection test project on GitHub but not seeing exactly what I need. What I want to do is:

services.AddScoped<IDataCatalogRepository, SqlDataCatalogRepository>("connectionString")

SqlDataCatalogRepository does have connectionString as one of its constructor properties.

Using Beta 4, any ideas?

Steven M.

Upvotes: 2

Views: 2171

Answers (2)

Matthew Allen
Matthew Allen

Reputation: 589

I just answered something very similar here: https://stackoverflow.com/a/39252582/1905693


I have a constructor in my repository class that accepts the db connection string as a parameter. This works for me when I add my repository for injection. In ConfigureServies() of the startup.cs file add this:

services.AddScoped<IRepos>(c => new Repos(Configuration["DbConnections:ConnStr1"]));

IRepos.cs is the interface, Repos.cs is the class that implements it. And of course Configuration is just a reference to the built IConfigurationRoot object.

Upvotes: 1

Marko M.
Marko M.

Reputation: 789

What you need is a factory. AddScoped method you use have few overloads including ones with implementationFactory parameter.

Your code would look something like this:

private static readonly Func<IServiceProvider, IDataCatalogRepository> repoFactory = (_) => 
{
    var connectionString = "get your connection string from somewhere";
    return new SqlDataCatalogRepository(connectionString);
}

And then just calling AddScoped like this:

services.AddScoped<IDataCatalogRepository>(repoFactory);

Upvotes: 7

Related Questions