views:

103

answers:

0

I've been using unity with interfaces, but sometimes created an interface only to use a single method in a single class; and used unity as my IoC framework. But then I saw this post:

http://codebetter.com/blogs/karlseguin/archive/2009/05/08/making-the-untestable-testable-with-anonymous-methods-and-dependency-injection.aspx

which made me realize it would be better to inject only the method I want to use in this case. I created a class which receives anonymous functions and execute them, and couldn't find a way to configure unity to inject them in my config file.

This is my class which receive anonymous functions

public class Printer
{
    private Func<string> messageCreator;
    private Action<string> messagePrinter;

    public Printer(Func<string> messageCreator, Action<string> messagePrinter)
    {
        this.messageCreator = messageCreator;
        this.messagePrinter = messagePrinter;
    }

    public void Print()
    {
        messagePrinter(messageCreator());
    }

}

These implement the anonymous functions

public class FileReader
{
    public FileReader()
    { }

    public string GetMessage()
    {
        return "This came from file...";
    }
}



public class ScreenPrinter
{
    public ScreenPrinter()
    { }

    public void Print(string msg)
    {
        Console.WriteLine("Screen: {0}", msg);
    }
}

and this is how my main looks like:

    static void Main(string[] args)
    {
        IUnityContainer unityContainer = CreateContainer();

        FileReader fr = new FileReader();
        ScreenPrinter sp = new ScreenPrinter();

        unityContainer.RegisterInstance<Func<string>>(fr.GetMessage);
        unityContainer.RegisterInstance<Action<string>>(sp.Print);

        Printer printer = unityContainer.Resolve<Printer>();

        printer.Print();

        Console.ReadLine();
     }

This actually works and prints "Screen: This came from file...", but I wish I could do the injection via config file. Is it possible?