Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>();
like image 783
Rohit Avatar asked Sep 17 '25 06:09

Rohit


1 Answers

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"
  }

}
like image 185
Nkosi Avatar answered Sep 18 '25 20:09

Nkosi