I’m having some trouble conceptualizing what I’m supposed to do to facilitate communication between my class library and programs that use it — in this case, a Windows Forms app:
// Class in library
class Foo()
{
public Foo(){}
public void DoWork()
{
log("Working...");
}
private void log( string s )
{
Console.Writeline(s);
}
}
// Forms App
class Form1()
{
public Form1()
{
Foo MyFoo = new Foo();
MyFoo.DoWork();
}
}
Since there is nothing listening to the console in a winforms app, calls to log() show nothing. Is there a way to dynamically overwrite the Foo.Log method, or possibly assign a method with that signature to the Foo object that is more suitable for a forms app at runtime?
Thank you!
Declare a logger interface and inject a concrete logger into the library class
Use it like this
Where all these loggers implement the interface.
UPDATE
As Mike Panter has pointed out already, you can use a delegate
you can call it like this
Advantages of the delegate injection
See Jon Skeets article The Beauty of Closures for variable capturing.
Advantages of the interface injection