After talking about so many theories, we can manually implement a simple IOC framework, which can deepen the theoretical knowledge of IOC.
I. Ideas
When using the spring. NET Framework, we first need to instantiate the spring. Net container, and then call the GetObject method in the iobjectfactory interface of the IOC container to obtain 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. The object configured in the instance XML is required. We think of an instance that uses the reflection technology to obtain the object.
III,CodeImplementation
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 > ();
PublicMyxmlfactory (StringFilename)
{
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>
/// Get object
/// </Summary>
/// <Param name = "ID"> </param>
/// <Returns> </returns>
Public Object GetObject ( String ID)
{
Object Result = Null ;
If(Objectdefine. containskey (ID ))
{
Result=Objectdefine [ID];
}
ReturnResult;
}
}
}
2. Call
Program
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
NamespaceMyselfioc
{
ClassProgram
{
Static VoidMain (String[] ARGs)
{
Appregistry ();
Console. Readline ();
}
Static Void Appregistry ()
{
Myxmlfactory CTX = New Myxmlfactory ( @" D: \ objects. xml " );
Console. writeline (CTX. GetObject ( " Persondao " ). Tostring ());
}
}
}
Well, a simple IOC framework is basically implemented.
Code download
Returned directory