Tadija Bagarić Tadija Bagarić - 9 months ago 49
ASP.NET (C#) Question

Subscribe to an event raised by a Controller in other project

I have 2 projects in the same solution. One is an ASP.NET MVC application (A) and the other is a console application (C). I want C to subscribe to an event that will be raised by a controller in A. I am using a singleton class that raises the event and can take subscriptions to the event.

I subscribed to the event and checked (using a debugger) that the subscription is indeed stored and can confirm that the event gets raised at the right time.

The problem happens when I start using those projects together - even though C subscribes to the event, when A raises it the subscription is not in the EventHandler listener list so the event is not cought in C.

It is like my singleton goes out of scope or that the same instance is not used between projects. I kinda get the filling that I have two instances of my Singleton.

My goal is to receive an event from a controller in another project. Singleton class can be avoided if it is not necessary.

Any help is appreciated.

Controller (in project A)

public void ProcessCommandMessage(Message message)

MessageSpy (in project A)

private static readonly MessageSpy _instance = new MessageSpy();
public static MessageSpy Instance { get { return _instance; } }
static MessageSpy() { }
private MessageSpy() { }

public event EventHandler<Message> MessageReceived;

public virtual void OnMessageReceived(Message message)
if (MessageReceived != null)
MessageReceived(this, message);

Subscriber (in project C)

private void Run()
SlackMessageSpy.Instance.MessageReceived += Instance_MessageReceived;

static void Instance_MessageReceived(object sender, OutgoingHookMessage e)

Answer Source

You added a project reference to the web app from the console app I assume? This is not going to work. You have stated it correctly: you probably have two instances. Both are running in their own separated process and you should communicate between them using messaging.

You have very tight coupling between your web app and console app by using this SlackMessageSpy. You should decouple these events instead by using some messaging component like SignalR (https://www.asp.net/signalr) or Webhooks (https://docs.asp.net/projects/webhooks/en/latest/overview.html) for example. So the controller sends a SignalR message or calls a webhook and the console app subscribes to this message.

It might be as simple as to have the controller writing small files with the information to a location the console app has access to and have the console app read those files.