Preface
I haven't written on Weibo for a long time, because I decided to move from Beijing, where I have worked for more than three years, to Shanghai some time ago due to family reasons. Dependency injection has written similar things when learning net core, but it has little practiced. As a result, when we came to the Shanghai New Company System Framework, we involved this knowledge point, so after understanding our project, we decided to make some relevant summary. Next, let's first understand hewi dependency injection.
What is dependency injection
Dependency injection, the full name is "dependency injection into container". A container (IOC container) is a design pattern, and it is also an object. If you put a certain class (regardless of how many dependencies there are) into this container, you can "parse" an instance of this class. So dependency injection is to put a dependency class into a container (IOC container), and then parse an instance of this class. Key points: Dependency injection is a design pattern to achieve control inversion. [Now I know there are other design patterns besides gof. 】
Why use dependency injection
We want high cohesion and low coupling to program, so decoupling is the starting point of many theories, and the inversion of dependency injection control is also for decoupling. So let’s ask what is low coupling? My understanding is: during the programming process, we don’t need to know the content of components and class libraries, just know the interface they provide, and call the interface to implement functions. We just say that this situation is low coupling.
When you have not been exposed to dependency injection, the idea of decoupling is actually the gof design pattern and design principles. Many of the articles I have shared before involve encapsulation libraries are based on interface-oriented methods. For example:
public interface IOrder { //Product Product objectdecimal ValueProducts(params Product[] products); } public class Order : IOrder { public decimal ValueProducts(params Product[] products) { return (p => *); } }
The above is a base class that is often written in malls. For example, when we used to call the method of placing an order in the shopping cart in the mall, even if the total price is calculated.
public class ShoppingCart { //Calculate the total price of goods in the shopping cart public decimal CalculateStockValue() { Product[] products = { new Product {Name = "Dragon Teeth 2016 New", Number=2,ModelNo = 121,ColorID=65,SizeID=78, Price = 289.40}, new Product {Name = "Dragon Teeth 2017 New", ModelNo = 121,ColorID=65,SizeID=78, Number=2,Price =3800}, }; IOrder order = new Order(); //Calculate the total price of the product decimal totalValue = (products); return totalValue; } }
The above is the way I often use to handle my business needs. This interface-oriented approach, if we want to calculate the amount, if we change the way we want to calculate the amount, for example, our size 32 is 32 and the amount is 32, then we just need to increase the amount. Change the interface instantiation. If you don’t type the code, you should understand it (low coupling). Then we can see whether ShoppingCart depends on the interface and implementation. Now let’s consider a question. Although the shopping cart calls the interface instantiation, it also depends on order. So is there a way to reduce its dependency - that is, to completely separate them. Then the solution to this problem uses dependency injection. Key points: Dependency injection is to reduce dependence on interface instantiated objects. So how to implement dependency injection?
Implementation of construct injection
Through the constructor of the class
The first time I saw Net Core, others also talked about this method. Let’s take a look at the code below. Set a data member of the service class interface type and use the constructor as the injection point. This constructor accepts a specific service class instance as a parameter and assigns it to the data member of the service class interface type.
public class ShoppingCart { IOrder order; //Constructor, parameter is an example of the class that implements the IOrder interface public ShoppingCart(IOrder _order) { order = _order; } //Calculate the total price of goods in the shopping cart public decimal CalculateStockValue() { Product[] products = { new Product {Name = "Dragon Teeth 2016 New", Number=2,ModelNo = 121,ColorID=65,SizeID=78, Price = 289.40}, new Product {Name = "Dragon Teeth 2017 New", ModelNo = 121,ColorID=65,SizeID=78, Number=2,Price =3800}}; //Calculate the total price of the product decimal totalValue = (products); return totalValue; }
The second place in the above code is that ShoppingCart has nothing to do with the implementation order of the interface IOrder, and there is no need to understand how it is implemented. This is dependency injection. This is called construct injection.
When we discuss the next method of injection, there is a problem that has not been solved yet. "How do dependencies come about?" Writing dependencies as constructor parameters. Although this can be manually provided with this dependency, when the entire system is injected, it means that we need to know whether it meets each part of the needs (service locator). Is it a big deal? Then at this time we need to introduce a concept of "container" - dependency injection container.
protected override void RegisterBuilder(ContainerBuilderWrapper builder) { (builder);//Inject into storage <Order>().As<IOrder>(); }
The above is an implementation of the mvc container. AS is followed by the service class inheritance interface. In fact, my understanding of it is: if someone requests this type. We will give him an object of this type.
Attribute injection
In fact, there should be a lot of information related to dependency injection spring, so many knowledge points are also learned through Java theory. I did read the properties of the net book I understand.
If you need to use a certain attribute of the dependent object, the IoC container will automatically initialize the attribute after the dependent object is created.
First, set an interface
public interface Iorder { { //Product Product object decimal ValueProducts(params Product[] products); } }
Attribute injection is as follows:
public class ShoppingCart { private iordre _order; public iordre Order { get { return _order; } set { _order = value; } } public decimal ValueProducts(params Product[] products) { return (products); } }
Setter Injection
Set a data member of the service class interface type and set a Set method as the injection point. This Set method accepts a specific service class instance as a parameter and assigns it to the data member of the service class interface type. In fact, this injection method is more flexible and there are more users.
//Service interface internal interface IServiceClass { String ServiceInfo(); } //Service method internal class ServiceClassA : IServiceClass { public String ServiceInfo() { return "I am ServceClassA"; } } //Service method internal class ServiceClassB : IServiceClass { public String ServiceInfo() { return "I'm ServceClassB"; } } //Customer class implementation set internal class ClientClass { private IServiceClass _serviceImpl; public void Set_ServiceImpl(IServiceClass serviceImpl) { this._serviceImpl = serviceImpl; } public void ShowInfo() { (_serviceImpl.ServiceInfo()); } } //Call class Program { static void Main(string[] args) { IServiceClass serviceA = new ServiceClassA(); IServiceClass serviceB = new ServiceClassB(); ClientClass client = new ClientClass(); client.Set_ServiceImpl(serviceA); (); client.Set_ServiceImpl(serviceB); (); } }
Conclusion
In fact, there are many things that can be talked about in dependency injection. The emergence of net core dependency injection is an indispensable knowledge point. What you can talk about later are frameworks such as dependency injection and reflection, dependency injection and polymorphism, and dependency injection. . . . . . .
I haven't written a blog for a long time, and I'm not prepared enough. If you are interested, go online.
.net book words:
"asp net mvc5 Advanced Programming" "Dependency Injection in .NET" (no Chinese)
There should be more Java-related books. If you are interested, learn together.
The above is a detailed explanation of core dependency injection. For more information about core dependency injection, please follow my other related articles!