How to pass connection string to UnitOfWork project from startup.cs asp.net core

.net-core asp.net-core c# entity-framework-core

Question

I created constructor in AppDbContext and context is implement in UnitofWork which pass string to context but how can I pass connection string to at startup.cs when I register unitofwork. Repository and UnitOfWork are in different project

Following is my code,

connection string to constructor

private readonly string _connection;
public AppDbContext(string connection) 
{

    _connection=connection;

}

UnitOfWork constructor

public UnitOfWork(string connection)
{
    _context =  new AppDbContext(connection);
}

in StartUp.cs, can I pass the connection string below, reading from appsettings.json?

 services.AddTransient<IUnitOfWork, UnitOfWork>();
1
3
8/6/2017 7:00:54 PM

Accepted Answer

Don't do that. If already using DI then inject the context into the UOW and configure the context during startup.

public class UnitOfWork : IUnitOfWork {
    private readonly AppDbContext _context;
    public UnitOfWork(AppDbContext context) {
        _context =  context;
    }

    //...other code removed for brevity
}

And create the database context using the following example.

public class AppDbContext : DbContext {
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)  {
    }

    //...other code removed for brevity
}

You then register everything including the context with dependency injection

public void ConfigureServices(IServiceCollection services) {

    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddTransient<IUnitOfWork, UnitOfWork>();

    services.AddMvc();
}

configuration reads the connection string from the appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "connection string here"
  }

}
5
8/6/2017 6:53:20 PM


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