简体   繁体   中英

Opennetcf.IOC event subscription and inheritance

Class1 has event with attribute [EventPublication("event1")]. Class2 and Class3 inherits from Class1.

I want to subscribe Method1 to event in object from Class2 and Method2 to event in object from Class3 using [EventSubscription].

But in the derived classes there is the same EventPublication name of the event. So how to distinguish events in derived classes? Is it possible?

EDIT: Maybe I misunderstand some obvious things about IoC or I try to complicate simple solution... I will try to clarify my question. Here is some code:

class BasePresenter
{
    [EventPublication("event")]
    public event Action action;

    public void Run()
    {
        someAction();

        if (action != null)
            action();
    }

    protected virtual void someAction()
    {

    }
}

class Presenter1 : BasePresenter
{
    protected override void someAction()
    {

    }
}

class Presenter2 : BasePresenter
{
    protected override void someAction()
    {

    }
}

class AnotherClass
{
    [EventSubscription("event", ThreadOption.Caller)]
    public void action1()
    {
        System.Windows.Forms.MessageBox.Show("Presenter1 started");
    }

    [EventSubscription("event", ThreadOption.Caller)]
    public void action2()
    {
        System.Windows.Forms.MessageBox.Show("Presenter2 started");
    }
}

There is action1() and action2() methods in Another class. I would like to fire action1() when instance of Presenter1 Run() method is called and fire action2() when instance of Presenter2 Run() method is called. But calling Run() method will fire both methods action1 and action2.

I'm not certain I understand the question. There are two ends to the event aggregation, a Publisher and a Subscriber. They are "connected" by the string event name you use in the attribute and nothing else.

A subscription can be done in the same class as the publication, though it's not clear to me why you'd ever do that, just have the base class call a virtual method that the derived classes implement and you're done.

If you want to use events and you want to know if the event source instance is not the receiver instance, just check the event's source input parameter against this , something along these lines:

[EventSubscription("myevent")]
public void OnEvent(object sender, EventArgs a)
{
    if(sender.Equals(this)) return;

    // do stuff here - the event came from another class instance
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM