asp. net core dependency injection

  • 2021-11-13 07:12:36
  • OfStack

Preface

I haven't written Weibo for a long time, because some time ago, due to family reasons, I decided to move from Beijing, where I worked for more than 3 years, to Shanghai. Dependency injection has written something similar when learning net core, but it is less practiced. As a result, the system framework of Shanghai New Company involves this knowledge point, so I decided to make a related summary after understanding my own project. Next, let's take a look at hewi dependency injection.

What is dependency injection

Dependency injection, the full name is "dependency injection into container". The container (IOC container) is a design pattern, which is also an object. If you put a class (no matter how many dependencies) into this container, you can "parse" out the instance of this class. So dependency injection is to put a dependent class into a container (IOC container) and then parse out an instance of that class. Focus: Dependency injection is a design pattern to realize inversion of control. "Now you know there are other design patterns besides gof."

Why use dependency injection

We want high cohesion and low coupling in programming, so decoupling is the starting point of many theories, and dependency injection control inversion is also for decoupling. So take the liberty of asking 1. What is low coupling? My understanding is that in the process of programming, we don't need to know the contents of components and class libraries, but only need to know the interfaces they provide, and the functions can be realized by calling the interfaces, so we say this situation is low coupling.

In the absence of dependency injection, the idea of decoupling is actually the gof design pattern and design principles. Many articles I have shared before involve encapsulating class libraries based on interface-oriented methods. For example:


public interface IOrder
{
//Product  Product object 
decimal ValueProducts(params Product[] products);
}

public class Order : IOrder
{
public decimal ValueProducts(params Product[] products)
{
return products.Sum(p => p.Price*p.Number);
}
}

The above is a base class that is often written in the mall. For example, when we used to call the method of placing an order on a shopping cart even if it was the total price.


public class ShoppingCart
 {
  // Calculate the total price of goods in the shopping cart 
  public decimal CalculateStockValue()
  {
  Product[] products = {
  new Product {Name = " Dragon tooth 2016 New style ", Number=2,ModelNo = 121,ColorID=65,SizeID=78, Price = 289.40},
  new Product {Name = " Dragon tooth 2017 New style ", ModelNo = 121,ColorID=65,SizeID=78, Number=2,Price =3800},
  };
  IOrder order = new Order();
  // Calculate the total price of goods  
  decimal totalValue = order.ValueProducts(products);
  return totalValue;
  }
 }

These are my common ways to deal with my business needs. In this interface-oriented way, if the way we want to calculate the amount is changed, for example, we give a 30% discount on the amount of size 32, then we only need to add the amount class. Just change the interface instantiation. The code should be understood without typing (low coupling). Then we can see that ShoppingCart depends on the interface and implementation, so now let's consider a question. Although the shopping cart calls the interface instantiation, it also depends on order, so is there any way to reduce its dependency-that is, to separate them completely? Then dependency injection is used to solve this problem. Important point: Dependency injection is to reduce the dependence on interface instantiation objects. So how do you implement dependency injection?

Implementation of Construction Injection

Through the constructor of the class

Look at net core for the first time. Others also talk about this way. Look at the code below. Set a data member of the service class interface type, and take the constructor as the injection point. This constructor takes a concrete service class instance as the parameter and assigns it to the data member of the service class interface type.


public class ShoppingCart
 {
  IOrder order;
  // Constructor, the parameter is the implementation of the IOrder  An instance of the class of the 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 tooth 2016 New style ", Number=2,ModelNo = 121,ColorID=65,SizeID=78, Price = 289.40},
   new Product {Name = " Dragon tooth 2017 New style ", ModelNo = 121,ColorID=65,SizeID=78, Number=2,Price =3800}}; // Calculate the total price of goods 
  decimal totalValue = order.ValueProducts(products);
  return totalValue;
  }

The most second place of the above code is that ShoppingCart has nothing to do with the implementation of order of interface IOrder, so you don't need to know how it is implemented. This is dependency injection. This is called structural injection.

When we discuss the next injection method, there is a problem that has not been solved. "How does dependency come about?" Write dependencies as constructor parameters, although you can provide them manually with this, but when the whole system is dependent on injection, that means that we need to know how to meet the requirements of each 1 part of any 1 component (service locator), isn't it very big? Then we need to introduce a concept of "container"-----dependency injection container.


protected override void RegisterBuilder(ContainerBuilderWrapper builder)
 {
  base.RegisterBuilder(builder);        // Injection storage 
  builder.RegisterType<Order>().As<IOrder>();
 }

The above is one implementation of mvc container. AS is followed by the interface inherited by the service class, which I actually understand as: If someone requests this type. We'll give him this type of object.

Attribute injection

In fact, dependency injection spring related information should be a lot, so a lot of knowledge points are also through the theory of java used for reference. Attribute injection I did read the book net to understand.

If you need to use a property of a dependent object, the IoC container automatically initializes the property after the dependent object is created

First of all, 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 Order.ValueProducts(products);
  }
 }

Setter injection

Set a data member of the service class interface type, and set an Set method as the injection point. This Set method takes a concrete 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 am ServceClassB";
  }
 }
 // Customer class implementation set
 internal class ClientClass
 {
  private IServiceClass _serviceImpl;

  public void Set_ServiceImpl(IServiceClass serviceImpl)
  {
  this._serviceImpl = serviceImpl;
  }

  public void ShowInfo()
  {
  Console.WriteLine(_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.ShowInfo();
  client.Set_ServiceImpl(serviceB);
  client.ShowInfo();
  }
 }

Concluding remarks

In fact, there are many things to talk about dependency injection, and the emergence of net core dependency injection is an essential knowledge point. We can talk about dependency injection and reflection, dependency injection and polymorphism, and the framework of dependency injection. . . . . . .

I haven't written a blog for a long time, and I haven't prepared enough. If you are interested, go online and find it.

. words of net book:

"asp net mvc5 Advanced Programming" "Dependency Injection in. NET" (not in Chinese)

There should be more books related to java. If you are interested, learn 1 from 1.

The above is a detailed explanation of asp. net core dependency injection. For more information on asp. net core dependency injection, please pay attention to other related articles on this site!


Related articles: