person類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace t1_IoCTest
{
//說明:如果需要使用IoC,前提是這個類及使用這個類的地方,不在同一個程序集中
public interface IPerson
{
void Say();
}
public partial class Person:IPerson
{
//constructor
public Person()
{
}
public Person(string name)
{
Name = name;
}
public Person(int age)
{
Age = age;
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; set; }
public int Age { get; set; }
public Car MyCar { get; set; }
public List<String> MyCarList { get; set; } //String類型,若是Car類型,則配置文件中添加對另一注入屬性節點的引用
public void Say()
{
//Console.WriteLine("Hello {0},MyCar Brand:{1}",Name,MyCar.Brand);
foreach(var item in MyCarList){
Console.WriteLine(item);
}
}
}
public class Car
{
public string Brand { get; set; }
//重寫ToString方法
public override ToString(){
return Brand;
}
}
}
program。cs:main方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spring.Context;
using Spring.Context.Support;
using Spring.Core;
namespace t1_IoCTest
{
class Program
{
static void Main(string[] args)
{
//1、創建容器對象
IApplicationContext ctx = ContextRegistry.GetContext();
//2、聲明接口類型的變量
IPerson p;
//3、通過容器創建對象
//p = ((IObjectFactory) ctx).GetObject("Zxh") as IPerson;
p = ctx.GetObject<IPerson>("Zxh");
//4、完成對象成員的調用
p.Say();
Console.ReadKey();
}
}
}
app.config配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<description>An example that demonstrates simple IoC features.</description>
<!--type中逗號左邊是類的完整名稱,右邊是類的程序集的名稱-->
<object name="Zxh" type="t1_IoCTest.Person,t1_IoCTest">
<property name="MyCarList">
<list>
<value>jk</value>
<value>nll</value>
<value>yzk</value>
<!-- 若前面MyCarList爲List<Car>類型,則引用其他注入屬性 -->
<!-- <ref object="MyCar1"/> -->
</list>
</property>
</object>
<object name="MyCar1" type="t1_IoCTest.Car,t1_IoCTest">
<property name="Brand" value="BMW"/>
</object>
<object name="MyCar2" type="t1_IoCTest.Car,t1_IoCTest">
<property name="Brand" value="Audi"/>
</object>
</objects>
</spring>
</configuration>
集合屬性注入結果:
MyCarList改爲List<Car>類型後,輸出爲:
重寫Car類的ToString方法後 :