Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I design View logic into c# projects

I have three c# projects in my solution. One is a console app that simply calls into a class library project. The class library project does all the processing for the application. Then there is a WinForm project that displays a form and then when a button is pressed, calls the same logic in the class library project. As a result, there are two ways to run the logic, via the Console or via a Windows UI (WinForm).

My problem is that part way through the class library logic, if the UI app is being used, I want a custom WinForm form to appear to ask the user a question.

In the Console app, I want the same place in the logic to simply write out to the Console. In my understanding of architecture, you don't want the class library project to contain WinForm logic and require it to have references to all the WinForm references. But how do I make a call to the WinForms project (or something else) to display the custom WinForm form? There would be a circular reference where the class library would reference the main WinForm app and the WinForm app would reference the class library project.

What is the standard way of doing this?

like image 478
user31673 Avatar asked Jan 12 '10 16:01

user31673


1 Answers

You could create an interface that your library defines to communicate back to the caller, then have both your calling apps define their own implementaions of this interface, the library calls the methods on this interface and knows nothing of the implmentation.

The caller processes the methods accordingly...

public interface IProgressReporter
{
       void ReportMessage(string message);
}



public class WinFormsProgressReporter : IProgressReporter
{
    public void ReportMessage(string message)
    {
          MessageBox.SHow(message);
    }
}

public class ConsoleAppProgressReporter : IProgressReporter
{
    public void ReportMessage(string message)
    {
          Console.WriteLine(message);
    }
}

public class LibraryClass
{
    public static void SomeMethod(IProgressReporter rep)
    {
         rep.ReportMessage("Wooooohooooo!");
    }
}
like image 149
Richard Friend Avatar answered Sep 27 '22 18:09

Richard Friend