Welcome tag moderator AKA Unofficial DEV cheerleader. While most of my friends are found on SnapChat or Tic-Toc, you can find me here. And I OOP, but I’m not a VSCO girl.
Hi Katie, that's a good question and sorry for not specify that in the post. So, in Startup.cs class you declare all the bindings for knowing which implementation needs to be resolved for each interface. For the actual dependency injection, you could do it by passing the members in the constructor of your class, an example:
// MyController.cs
[ApiController, Route("api/[controller]")]
public class MyController : BaseController
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
}
// MyService.cs
public class MyService : IMyService
{
private readonly IMyRepository _myRepository;
public MyService(IMyRepository myRepository) -> here it gets injected
{
_myRepository = myRepository;
}
}
This is constructor injection (you also have other way like "field injection"). To summarize, you need to pass the interface via constructor and is going to be resolved to the desired class at runtime with whatever you have declared in your startup.
This allows you to have two different implementations but you are not coupled. One scenario could be that you have
IRepository with MySqlRepository and MongoDbRepository as implementations of that interface. Is recommended to always develop against an abstraction (in this case, IRepository) and resolve the desire implementation at runtime by any logic you need.
I hope this clarifies a little bit more. Let me know if it was helpful or if you need more info, I'm happy to help!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
If I have a Controller that takes a Service and that Service takes a Repository, how do I inject that Repository into the Service?
Hi Katie, that's a good question and sorry for not specify that in the post. So, in Startup.cs class you declare all the bindings for knowing which implementation needs to be resolved for each interface. For the actual dependency injection, you could do it by passing the members in the constructor of your class, an example:
This is constructor injection (you also have other way like "field injection"). To summarize, you need to pass the interface via constructor and is going to be resolved to the desired class at runtime with whatever you have declared in your startup.
This allows you to have two different implementations but you are not coupled. One scenario could be that you have
IRepository
withMySqlRepository
andMongoDbRepository
as implementations of that interface. Is recommended to always develop against an abstraction (in this case,IRepository
) and resolve the desire implementation at runtime by any logic you need.I hope this clarifies a little bit more. Let me know if it was helpful or if you need more info, I'm happy to help!