Asp.net core dependency injection
Dependency injection (DI) is a technology to realize loose coupling between objects and their partners or dependencies. Instead of instantiating the author directly or using static references, provide the object used to perform the action to the class in some way. Typically, classes declare their dependencies through their constructors, allowing them to follow the explicit Dependencies Principle, a method known as "constructor injection.".
Using the idea of DI in the design of class will make their dependencies more coupling, because they have no direct hard coding dependence on their partners. They follow the Dependency Inversion Principle "high-level modules should not rely on low-level modules, and both should rely on abstraction " Class is required to provide abstractions (usually interfaces) to them when they are constructed, rather than directly referring to specific implementations. Extracting the dependencies of interfaces and providing their implementation as parameters is also an example of Strategy design pattern.
Principle of dependency injection
//Contract an abstract interface
public interface IRepository
{
string GetInfo();
}
//Using EF to implement the interface
public class EFRepository : IRepository
{
public string GetInfo()
{
return "load data form ef!";
}
}
//Using dapper to implement the interface
public class DapperRepository : IRepository
{
public string GetInfo()
{
return "load data form dapper!";
}
}
//Provides an abstract interface in the constructor of the service used to perform the operation
public class OperationService
{
private readonly IRepository _repository;
public OperationService(IRepository repository)
{
_repository = repository;
}
public string GetList()
{
return _repository.GetInfo();
}
}
From the above code, it can be seen that there is no strong dependency between service and repository, but both of them are related to the abstract interface irepository.