4

In my asp.net core solution I have 2 projects: asp.net app and library with model layer which contains pattern repository.

I ask DI in app realize my interface

services.AddTransient<IRepositrory, Repository>();

But! Repository constructor has parameter

public Repository(string connectionString)
{
    _appDBContext = new AppDBContext(connectionString);
}

How correctly configure DI to create repository with specific string from appsettings.json (asp.net app)?

2
  • 4
    Your repository class should get AppDbContext injected as a dependency. What you have now is not proper DI design Commented Jul 8, 2016 at 18:09
  • public Repository(IDBContext dbContext) something like this? Commented Jul 8, 2016 at 20:26

4 Answers 4

4

There is an overload that accepts an implementation factory

services.AddTransient<IRepository>(isp => new Repository(conn));

You can get the connection string using

Configuration.GetConnectionString("DefaultConnection")
Sign up to request clarification or add additional context in comments.

Comments

3

You can also use AddInstance method:

var connectionString=Configuration.GetConnectionString("DefaultConnection");
services.AddInstance<IRepository>(new Repository(connectionString));

But I'm agree with @MikeSW what he said in his comment above. You should register your DbContext and use it as parameter in your repository constructor:

 services.AddDbContext<AppDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

And your constructor would be:

public Repository(AppDBContext context)
{
    _appDBContext = context;
}

Comments

0

you should be putting the services in ConfigureServices method of Startup.cs

    public Startup()
    {
        var builder = new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json");
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<MyDbContext>(
            options => options.UseSqlServer(Configuration["database:connection"]));
     }

Where appsettings.json:

{
"database": {
"connection":  "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MyDb"
   }
 }

Comments

0
services.AddTransient<IRepository>(isp => new Repository(connection));

Use this for accepts an implementation factory and to retrieve connection string use this:-

Configuration.GetConnectionString("DefaultConnection") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.