Spring. NET 학습 노트 (3) - 등록 이벤트 주입

7299 단어 spring
이벤트 주입 은. 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);

    }

}

 
서버 테스트
[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).");

}

좋은 웹페이지 즐겨찾기