Circular Dependency in Two Projects in C#

后端 未结 4 1305
轻奢々
轻奢々 2020-12-20 12:42

I have two projects in a solution named ProjectA (ConsoleApplication) and ProjectB (ClassLibrary). ProjectA has a reference to ProjectB. Generally speaking, ProjectA calls a

4条回答
  •  清酒与你
    2020-12-20 13:12

    I suggest you to use events and listeners. You can, for example, send messages from ProjectB through Trace.WriteLine while, in ProjectA, you would add a subscriber for the trace. .NET already offers a ConsoleTraceListener class, to route Trace messages to the Console. You can add a listener from ProjectA through:

    Trace.Listeners.Add(new ConsoleTraceListener());
    

    Alternatively, if you don't want to use the integrated classes, you can build a very simple "source" class in ProjectB which will exposes an event with Action as its signature (although I'd suggest you to create a delegate for it), then subscribe to it from ProjectA. Generally, .NET classes are more flexible.

    ProjectB

    public static class MyTrace
    {
        public static event Action MessageReceived;
    
        internal static void Broadcast(string message)
        {
            if (MessageReceived != null) MessageReceived(message);
        }
    }
    

    ProjectA

    MyTrace.MessageReceived += s =>
    {
        /*Operate*/
    };
    

提交回复
热议问题