Create Ioc wheels step by step (1): What is Ioc, and create ioc wheels step by step

Source: Internet
Author: User

Create Ioc wheels step by step (1): What is Ioc, and create ioc wheels step by step
 Create an Ioc wheel directory step by stepStep by step create an Ioc wheel (1): What is Ioc?Create an Ioc wheel step by step (2): Detailed description of generic factories

 

  Preface

The. net core official version was released two days ago.

I was a little nervous when I wrote my blog for the first time. I don't know how to pretend that I often write it (:

For the first time, create a small wheel, Ioc container, and use this to improve your own class library.

What is the name of DI, Ioc, or anything on the tall?

I am not an old driver. Opening C # is not a long time. The following is my rough personal opinion. If I say wrong, I should face it a little lighter. After all, I still want to eat with my face (:

For fear of unsatisfactory words, let's use an example to illustrate it. The old driver will bypass it.

Xiao Huang is the main process of an e-commerce company. One day, the boss said that we should send a text message to the customer via SMS.

So Xiao Huang signed a contract with an SMS channel supplier called XSMS.

Then Xiao Huang wrote the start code.

First, write an XSMS class.

Public class XSMS {private string sign; public XSMS (string key, string pwd) {sign = "all e-commerce companies";} private string FormatTpl (string tpl, string msg, long phoneNumber, string client, string sign) {return tpl. replace ("$ sign", sign ). replace ("$ msg", msg ). replace ("$ client", client);} public void Send (string msg, long phone, string client, string tpl) {// signature and so on. Send the text message to the complex sending code Console of the xsms company Interface // XXX. writeLine ("text message from XSMS:" + FormatTpl (tpl, msg, phone, client, sign ));}}

Then, I started writing business calls.

Public static void Main (string [] args) {Encoding. registerProvider (CodePagesEncodingProvider. instance); while (true) {SendMsg2Client (); Thread. sleep (1000*60) ;}} private static void SendMsg2Client () {var cs = GetClient (); if (cs! = Null & cs. count> 0) {string tpl = "[$ sign] $ client Hello, $ msg"; var sms = new XSMS ("123", "666 "); foreach (var c in cs) {sms. send ("your inflatable girlfriend has been shipped, please use it after checking", c. key, c. value, tpl) ;}} private static void SetSend (long phone) {// Mark sent text messages to the database} private static Dictionary <long, string> GetClient () {// return new Dictionary <long, string >{{ 13666666666, "group owner "}};}

Okay, the business is going online, and the boss is very satisfied.

After more than half a month, the boss found Xiao Huang: Xiao Huang. My friend sent a text message with only 4.5 points. How can I get 6 points for the channel you signed, let's change it to the interface of his company. I will give QQ to the technician of his company. contact him.

Xiao Huang found a technician from his boss and friend's company and asked him to use his company account to send text messages,

Okay, Xiao Huang started to work overtime again.

Public class FriendSMS {private string sign; public FriendSMS (string key, string pwd) {sign = "all e-commerce companies";} private string FormatTpl (string tpl, string msg, long phoneNumber, string client, string sign) {return tpl. replace ("$ sign", sign ). replace ("$ msg", msg ). replace ("$ client", client);} public void Send (string msg, long phone, string client, string tpl) {// signature and so on. Send the text message to the complex sending code Console of the interface provided by the boss and friend company. // XXX. writeLine ("text message from FriendSMS:" + FormatTpl (tpl, msg, phone, client, sign ));}}

Complete the SMS code and modify the Business Code.

Private static void SendMsg2Client () {var cs = GetClient (); if (cs! = Null & cs. count> 0) {string tpl = "[$ sign] $ client Hello, $ msg"; string key = "123 "; // obtain string pwd = "666" from the configuration file or database; // obtain var sms = new FriendSMS (key, pwd) from the configuration file or database ); // use the foreach (var c in cs) {sms. send ("your inflatable girlfriend has been shipped, please use it after checking", c. key, c. value, tpl );}}}

 

Okay, the business is going online, and the boss is satisfied, that is, Xiao Huang is tired. It is a bit difficult to test: You have changed the Business Code and asked me to re-test the entire business, you need to ask me for health care after work.

After the business was launched for one month, the boss called Xiao Huang to the office: Xiao Huang, why did you always say that he couldn't receive the text message? What junk code did you write? It's so unstable.

Xiao Huang argues: Boss, it's none of my business. It's because the interface provided by your friend company is always unstable and we often eat our text messages. I told them about the data every day, I have learned about their technology. They use Alibaba's big fish interface. They wrote a proxy interface for us to use, it's better to use Alibaba's big fish interface directly. Similarly, it's a 4.5-minute text message. Direct Connection is certainly much more stable and will not be subject to your friend's company.

Boss: Okay, you have done this. Please take care of yourself.

This time, Xiao Huang learned how to make the Business Code as much as possible instead of modifying it. Baidu asked me some questions from the group, xiao Huang decided to use a simple implementation: factory Model

Xiao Huang began to refactor the code, and XXSMS operations were the same. I want to abstract an interface.

    public interface ISMS    {        void Init(string key, string pwd);        void Send(string msg, long phone, string client, string tpl);    }

Write the code of Alibaba big fish and modify the code of the previous two channels

Public abstract class BaseSMS: ISMS {public virtual void Init (string key, string pwd) {throw new NotImplementedException ();} public virtual void Send (string msg, long phone, string client, string tpl) {throw new NotImplementedException ();} protected string FormatTpl (string tpl, string msg, long phoneNumber, string client, string sign) {return tpl. replace ("$ sign", sign ). replace ("$ msg", msg ). replace ("$ client", client) ;}} public class AlidayuSMS: BaseSMS {private string sign; public override void Init (string key, string pwd) {sign = "all e-commerce companies";} public override void Send (string msg, long phone, string client, string tpl) {// signature and so on. Send the text message to the complex sending code Console of the xsms company Interface // XXX. writeLine ("send a text message from Alibaba big fish:" + FormatTpl (tpl, msg, phone, client, sign) ;}} public class XSMS: BaseSMS {private string sign; public override void Init (string key, string pwd) {sign = "all e-commerce companies";} public override void Send (string msg, long phone, string client, string tpl) {// signature and so on. Send the text message to the complex sending code Console of the xsms company Interface // XXX. writeLine ("text message from XSMS:" + FormatTpl (tpl, msg, phone, client, sign) ;}} public class FriendSMS: BaseSMS {private string sign; public override void Init (string key, string pwd) {sign = "all e-commerce companies";} public override void Send (string msg, long phone, string client, string tpl) {// signature and so on. Send the text message to the complex sending code Console of the interface provided by the boss and friend company. // XXX. writeLine ("text message from FriendSMS:" + FormatTpl (tpl, msg, phone, client, sign ));}}

 

Then write a simple factory

Public class SMSFactory {public static ISMS GetSMS (string type) {switch (type. trim (). toLower () {case "xsms": return new XSMS (); case "friendsms": return new FriendSMS (); case "alidayusms": return new AlidayuSMS ();} throw new Exception ("nonexistent SMS channel:" + type + "");}}

Modify Business Code

Private static void SendMsg2Client () {var cs = GetClient (); if (cs! = Null & cs. count> 0) {string tpl = "[$ sign] $ client Hello, $ msg"; string key = "123 "; // obtain string pwd = "666" from the configuration file or database; // obtain string type = "alidayusms" from the configuration file or database "; // obtain var sms = SMSFactory from the configuration file or database. getSMS (type); sms. init (key, pwd); foreach (var c in cs) {sms. send ("your inflatable girlfriend has been shipped, please use it after checking", c. key, c. value, tpl );}}}

Going online, very stable and cheap, and the boss was very satisfied. He gave 50 Xiao Huang to go to health care. Xiao Huang gave the opportunity for health care to the test, because the test turned a little angry, the Business Code should be tested, and several original Channel interfaces should also be tested

Then one day, Alibaba noticed that the open platform interface should be changed to HTTPS. When Xiao Huang heard the message, He sneered and said, don't you just change the class?

Then Xiao Huang modified the category of Ali big fish and prepared to go online. The test heard this message: Mom, when I am transparent, I will go online after skipping it.

Xiao Huang argues: I just changed the category of Ali big fish.

Test: No. Your factory depends on the big fish and the generated DLL is re-compiled. I don't know if there is any problem with the original service.

Xiao Huang secretly complained, isn't it a way to lie to health care?

Once again, the test pitted a big health care, Xiao Huang complained to the group, saying that the test was hard for himself, and the crowd also condemned the test,

However, one of the old drivers said: this is what you are looking for. You cannot blame the test. You should decouple the Business Code from these text message modules and do not rely on these modules.

Xiao Huang: old driver. How can this problem be solved?

Old DRIVER: Dependency inversion makes this business and your "Factory" have nothing to do with various SMS classes. After an SMS class starts a project and generates a DLL, you can change the class to that project, add a new project when adding a class, and the module project will be handed over to the test.

Xiao Huang: The factory also needs to be re-compiled. The test will also cause me trouble.

Old DRIVER: upgrade your factory to a reflection factory or use the Ioc container in another step. What kind of text message module is required for the upgrade factory or Ioc container, the factory or Ioc container does not need to be changed at all, and the Business Code does not need to be moved at all. It will be easy to test in the future. In minutes, please go to health care.

Xiao Huang and many Members: Student, student card

Under the guidance of this idea of dependency inversion, Xiao Huang finds an Ioc container and writes the SMS module to the configuration file of the Ioc container.

Then, modify the Business Code for the last time.

Private static void SendMsg2Client () {var cs = GetClient (); if (cs! = Null & cs. count> 0) {string tpl = "[$ sign] $ client Hello, $ msg"; string key = "123 "; // obtain string pwd = "666" from the configuration file or database; // obtain var ctx = new IocContainer ("cfg. xml "); var sms = ctx. resolve <ISMS> (); // extracts implementation class sms from the Ioc container. init (key, pwd); foreach (var c in cs) {sms. send ("your inflatable girlfriend has been shipped, please use it after checking", c. key, c. value, tpl );}}}

Xiao Huang modified the code and ensured that the Business Code will not be moved in the future. In the future, it will be okay to test the implementation module only. After going online and running, testing evil smile picked up the soap on the ground (Escape

 

Well, after the above is a fictitious story, I believe everyone understands the factory, Ioc, DI, etc.

DI (Dependency Injection, Dependency Injection)

I Don't Know What Baidu means when I look at this name. Let's take a look at the related concepts first.

Dependence Inversion Principle (DIP)

Damn, there is another concept. If we introduce this concept, we need to introduce another one:Decoupling

What is decoupling? The meaning of decoupling is also clear. Decoupling removes coupling between software modules so that one module does not depend on another module.

In the above case, decoupling removes the coupling between the Business Code and various SMS modules. The business and the specific implementation modules are completely independent. In the first version, when the business is in the encoding stage, it is coupled with various SMS classes. It relies heavily on the SMS class and on the encoding stage.

After the Ioc is used to abstract the interface, this dependency does not exist in the coding stage. The SMS dependent on the call implementation occurs in the system running stage, and the dependency is in the running stage, ioc completely reversed the dependency, removed coupling, and put the dependency upside down.

IoC (Inversion of Control, Control Inversion)

The concept of Ioc is similar to the dependency inversion, which is the transfer of control. Originally, the Business Code decided to use the SMS module to transfer the Ioc container to decide which SMS module to use according to the configuration file, the control is transferred to the Ioc framework.

The Ioc container implemented by Ioc idea is responsible for the configuration fileInject dependency (DI)The module is returned to the container for business calling.

Simply put, the Ioc container is a luxury edition factory, an automated assembly factory, and the factory knows what it is, that is, I will send you the product specifications, you give me the product, no matter how you make the product, no matter what materials you use, I just need to meet my specifications.

Ioc is such a factory. We call the Ioc container (factory) in the Business Code, send the requirement (Product Specification) to the Ioc container, and the container returns the implementation class (product) to the business, the business can develop the product according to this specification.

The Ioc container is responsibleInject dependencyModule

Superficial insights, face light

Goal

Of course, the environment is under. net core.

Support configuration files

Supported registration Singleton

Support for delayed Loading

I am not a title party. Using. net magic can really be a direct new speed. Of course, this one-tier call will definitely drop a little bit, but the speed is higher than that of the reflected type.

 

To be continued, I will not be eunuch. I am not advertising for big fish.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.