Reputation: 492
I wrote a simple Data access interface with generic CRUD operations so that every database repository has to implement this interface. For now I implemented this interface for one database say SQL. This SQL implementation of the database takes database settings(connection string and other details) as parameter in it's constructor.
See below code:
namespace MyDataAccessInterfaces
{
public interface IDataAccess
{
read();
create();
update();
delete();
}
}
namespace MyDataAccessImplementations
{
public class SQLAccess
{
SQLAccess(Settings settings){
//do something to get DB context
}
//some properties here
read(){//some code
}
create(){//some code
}
update(){//some code
}
delete(){//some code
}
}
}
Now I want to dependency inject this into a Service controller. I'm looking at constructor dependency injection here. If I pass SQL implementation as dependency in controller constructor as below and add this in startup class->ConfigureServie method, how to pass it's settings?
public class HomeController : APIController
{
private readonly IDataAccess _dataAccess;
public HomeController(IDataAccess dataAccess)
{
_dataAccess= dataAccess;
}
public IActionResult Index()
{
//do something and set result
return Ok(result);
}
}
Below is my ConfigureService method in startup.cs class
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddSingleton<IDataAccess, SQLAccess>();
}
Question is, How do I pass the constructor parameters and property values in API's Configure Service method?
Upvotes: 1
Views: 3062
Reputation: 4236
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddSingleton<IDataAccess, SQLAccess>(opt=> { new SQLAccess(new
Settings(){
//Set Settings object properties here
});
});
}
Upvotes: 1