// Dataaccess. IOC. CS
Using system;
Using system. collections;
Using system. Collections. Generic;
Using system. text;
Using system. configuration;
Using system. reflection;
Namespace dataaccess. IOC
{
Public class objectinstancefactory
{
/// <Summary>
/// Service instance list
/// </Summary>
Private Static list <Object> objects = new list <Object> ();
Private Static list <string> objectsindex = new list <string> ();
/// <Summary>
/// Obtain a specified instance
/// </Summary>
/// <Param name = "assemblyname"> </param>
/// <Param name = "classname"> </param>
/// <Returns> </returns>
Public static object getobjectinstance (string assemblyname, string classname)
{
Object objectinstance = NULL;
Try
{
// Obtain the namespace and class name from the configuration file
String configpath = appdomain. currentdomain. basedirectory. tostring () + "configioc. config ";
Assemblyname = configioc. getconfigvalue (configpath, assemblyname );
Classname = configioc. getconfigvalue (configpath, classname );
String fullpath = assemblyname. Trim () + "." + classname. Trim ();
// Obtain the instance from the service list. If no instance exists, create an instance and return it. At the same time, put the instance into the service list.
Int Index = objectsindex. indexof (fullpath );
If (index> = 0)
Objectinstance = objects. toarray (). getvalue (INDEX );
If (objectinstance! = NULL)
Return objectinstance;
// Create a new instance because the instance service list does not have an instance
Objectinstance = createobjectinstance (assemblyname, classname );
// Add a new instance to the service list
If (objectinstance! = NULL)
{
Objects. Add (objectinstance );
Objectsindex. Add (fullpath );
}
}
Catch (exception ex)
{
Throw new exception (ex. Message );
}
Return objectinstance;
}
/// <Summary>
/// Create a specified instance
/// </Summary>
/// <Param name = "assemblyname"> </param>
/// <Param name = "classname"> </param>
/// <Returns> </returns>
Private Static object createobjectinstance (string assemblyname, string classname)
{
Object objectinstance = NULL;
Try
{
String fullpath = assemblyname. Trim () + "." + classname. Trim ();
Objectinstance = assembly. Load (assemblyname). createinstance (fullpath );
}
Catch (dllnotfoundexception ex)
{
Throw new exception (ex. Message );
}
Return objectinstance;
}
}
}
// Test. CS
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace testconsole
{
Class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("start ...");
Console. Readline ();
Dataaccess. Contract. idataaccesshelper dataaccess =
(Dataaccess. Contract. idataaccesshelper) dataaccess. IOC. objectinstancefactory. getobjectinstance ("dataaccess. Service", "servicehelper ");
String serialno = dataaccess. getmaxbillserialno ("purchase order", "CG ");
Console. writeline ("Ticket No.:" + serialno );
Console. Readline ();
Console. Readline ();
}
}
}