代码改变世界

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

  Clingingboy  阅读(1350)  评论(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).");
}
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示