Spring.NET学习笔记(3)-注册事件注入

K.Spring.net 专栏收录该内容
6 篇文章 0 订阅

    事件注入是.net版本的spring特有的,其实现方式是反向的,同时支持静态事件和实例事件

<object id="source" type="Spring.Objects.TestObject, Spring.Core.Tests"/>

<object id="staticEventListener" type="Spring.Objects.TestEventHandler, Spring.Core.Tests">
  <!-- wired up to a static event -->
  <listener event="StaticClick" method="HandleEvent">
      <ref type="Spring.Objects.TestObject, Spring.Core.Tests"/>
  </listener>
</object>

<object id="instanceEventListener" type="Spring.Objects.TestEventHandler, Spring.Core.Tests">
  <!-- wired up to an event exposed on an instance -->
  <listener event="Click" method="HandleEvent">
      <ref object="source"/>
  </listener>
</object>

internal class TestEventHandler 
    {
        public virtual void HandleEvent (object sender, EventArgs e) 
        {
            _eventWasHandled = true;
        }

        public virtual bool EventWasHandled 
        {
            get 
            {
                return _eventWasHandled;
            }
        }

        protected bool _eventWasHandled;
    }

 

public event EventHandler Click;

public static event EventHandler StaticClick;

/// <summary>
/// Public method to programmatically raise the <event>Click</event> event
/// while testing.
/// </summary>
public void OnClick()
{
    if (Click != null)
    {
        Click(this, EventArgs.Empty);
    }
}

/// <summary>
/// Public method to programmatically raise the <b>static</b>
/// <event>Click</event> event while testing.
/// </summary>
public static void OnStaticClick()
{
    if (TestObject.StaticClick != null)
    {
        TestObject.StaticClick(typeof (TestObject), EventArgs.Empty);
    }
}

 

Server测试

[Test]
public virtual void InstanceEventWiring()
{
    DefaultListableObjectFactory factory = new DefaultListableObjectFactory();
    XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(factory);
    reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("event-wiring.xml", GetType()));
    ITestObject source = factory["source"] as ITestObject;
    TestEventHandler instanceHandler = factory["instanceEventListener"] as TestEventHandler;
    // raise the event... handlers should be notified at this point (obviously)
    source.OnClick();
    Assert.IsTrue(instanceHandler.EventWasHandled,
                  "The instance handler did not get notified when the instance event was raised (and was probably not wired up in the first place).");
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

clingingboy

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值