This article describes three ways to create an IOC container,
Constructor mode
These conditions are required to create objects through the constructor:
- Indicates the object type Type= "class full name, assembly name" (
- There is a parameterless constructor or a default constructor (the dependency injection requires an externally callable constructor, such as a PUBILC-modified constructor, which can take parameters).
<!--构造器--> <object id="personDao" type="CreateObjects.PersonDao, CreateObjects" /> /// <summary> /// 构造器创建 /// </summary> static void CreateByConstructor() { string[] xmlFiles = new string[] { "assembly://CreateObjects/CreateObjects/Objects.xml" }; IApplicationContext context = new XmlApplicationContext(xmlFiles); IObjectFactory factory = (IObjectFactory)context; Console.WriteLine(factory.GetObject("personDao").ToString()); }
- The creation of nested type objects requires the "+" sign to concatenate the nested types. If the type person is nested in the Persondao
<!--嵌套类型--> <object id="person" type="CreateObjects.PersonDao+Person, CreateObjects" />
Static Factory mode:
Creating an object using a static factory requires configuring the Factory-method property
<!--静态工厂--> <object id="staticObjectsFactory" type="CreateObjects.StaticObjectsFactory, CreateObjects" factory-method="CreateInstance"/>
Instance Factory creation:
Creating an object using an instance factory requires defining a factory and then setting the Factory-object and Factory-method properties, and the object that satisfies the instance factory method must also be configured in the same container (or parent container) and the object definition cannot contain the type attribute
<!-- 实例工厂 --> <object id="instanceObjectsFactory" type="CreateObjects.InstanceObjectsFactory, CreateObjects" /><!--工厂--> <object id="instancePersonDao" factory-method="CreateInstance" factory-object="instanceObjectsFactory" /> <!--创建的对象-->
Create a spring.net IOC container in your project