Reputation: 332
How I can inject service with parameter in startup.cs. How to inject SqlConneciton?
public class AirportService : IAirportService
{
public AirportService(SqlConnection con)
{
var airportRepository = new AirportRepository<Airport>(con);
}
}
Upvotes: 1
Views: 849
Reputation: 2756
First of all you have to register your service like this:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IMyService, MyService>();
}
Only then constructor injection will be possible. In your example you would need to register your SqlConnection with an interface (like in above example). Then framework will create new instance when injecting this.
Regarding dependency injection I suggest you to take a look first here: Dependency Injection
BUT! I don't known if injecting of SqlConnection is a good approach. I would suggest to create some kind of factory ConnectionFactory: IConnectionFactory
, inject this, and then create new connection (take one from pool) using that ConnectionFactory
.
Upvotes: 2