After talking about so many theories, we can manually implement a simple IOC {
Tagshow (Event)
} "> Framework, which can deepen the theoretical knowledge of IOC.
I. Ideas
When we use the spring. NET Framework, we first need to instantiate the spring. Net container, and then call the IOC container iobjectfactory {
Tagshow (Event)
} "> The GetObject method in the interface gets the objects in the container. This tells us that to create an IOC container, We need to write a method to get the content of the XML file and declare a dictionary <string, Object> to store the objects in the IOC container, you also need to write a method that can get an object from dictionary <string, Object>.
Ii. Analysis
To get the content of an XML file, in the 3.5 syntax, I naturally came up with the ability to write data in the following format. {
Tagshow (Event)
} "> For the configuration object, we thought of using the reflection technology to obtain the object instance.
Iii. Code Implementation
1. xml Factory
Myxmlfactory
- Using system;
- Using system. Collections. Generic;
- Using system. LINQ;
- Using system. text;
- Using system. xml. LINQ;
- Using system. reflection;
- Namespace myselfioc
- {
- Public class myxmlfactory
- {
- Private idictionary <string, Object> objectdefine = new dictionary <string, Object> ();
- Public myxmlfactory (string filename)
- {
- Instanceobjects (filename); // instance IOC container
- }
- /// <Summary>
- /// Instance IOC container
- /// </Summary>
- /// <Param name = "FILENAME"> </param>
- Private void instanceobjects (string filename)
- {
- Xelement root = xelement. Load (filename );
- VaR objects = from OBJ in root. Elements ("object") Select OBJ;
- Objectdefine = objects. todictionary (
- K => K. Attribute ("ID"). value,
- V =>
- {
- String typename = V. Attribute ("type"). value;
- Type type = type. GetType (typename );
- Return activator. createinstance (type );
- }
- );
- }
- /// <Summary>
- /// Obtain the object
- /// </Summary>
- /// <Param name = "ID"> </param>
- /// <Returns> </returns>
- Public object GetObject (string ID)
- {
- Object result = NULL;
- If (objectdefine. containskey (ID ))
- {
- Result = objectdefine [ID];
- }
- Return result;
- }
- }
- }
Copy code
2. Call
Program
- Using system;
- Using system. Collections. Generic;
- Using system. LINQ;
- Using system. text;
- Namespace myselfioc
- {
- Class Program
- {
- Static void main (string [] ARGs)
- {
- Appregistry ();
- Console. Readline ();
- }
- Static void appregistry ()
- {
- Myxmlfactory CTX = new myxmlfactory (@ "D: \ objects. xml ");
- Console. writeline (CTX. GetObject ("persondao"). tostring ());
- }
- }
- }
Copy code
Well, a simple IOC framework is basically implemented.