2

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.

1

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Just what I was about to type up! Though, you can pass the factory delegate directly to the AddScoped call, and I'd suggest moving the connection string logic out of the delegate for efficiency depending on the source.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.