有几年没用spring.net了,下星期打算在项目里面用一下,毕竟注入能力太强大了。
首先还是用NuGet引用一下 Install-Package Spring.Core
下面创建三个类,其中一个类包含另外两个类作为属性
namespace SpringNetPropertyInject
{
public class GameChannel
{
public string ChannelName { set; get; }
public string ChannelId { set; get; }
}
}
namespace SpringNetPropertyInject
{
public class ChannelAccount
{
public string AccountName { set; get; }
public string AccountId { set; get; }
}
}
namespace SpringNetPropertyInject
{
public class Test
{
public GameChannel Channel { set; get; }
public ChannelAccount Account { set; get; }
public void ShowName()
{
MessageBox.Show(Channel.ChannelName + Account.AccountName);
}
}
}
我不太喜欢在app.config文件里面配置东西,因为会把那个文件搞得很臃肿,下面用object.xml文件进行配置
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object id="GameChannel" type="SpringNetPropertyInject.GameChannel">
<property name="ChannelName" value="某某渠道"/>
</object>
<object id="ChannelAccount" type="SpringNetPropertyInject.ChannelAccount">
<property name="AccountName" value="某某账户"/>
</object>
<object id="Test" type="SpringNetPropertyInject.Test">
<property name="Channel" ref="GameChannel"/>
<property name="Account" ref="ChannelAccount"/>
</object>
</objects>
值得注意的是这两句
<property name="Channel" ref="GameChannel"/>
<property name="Account" ref="ChannelAccount"/>
Channel 为Test类里面的属性名称,它的注入配置节叫GameChannel,也就是下面这个
<object id="GameChannel" type="SpringNetPropertyInject.GameChannel">
<property name="ChannelName" value="某某渠道"/>
</object>
这样把对象属性的属性也注入了,接着在程序中调用
using System;
using System.Windows.Forms;
using Spring.Context.Support;
namespace SpringNetPropertyInject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var context
= new XmlApplicationContext(Application.StartupPath + @"\object.xml");
var test = context.GetObject("Test") as Test;
if (test != null)
test.ShowName();
}
}
}
可以看到,对象已被成功注入了