1

I've written a WPF app that has two different main windows. I don't know which one to launch until runtime by looking up what kind of user is using the program in a database. The code I currently have works but Castle Windsor is doing tons of extra work by newing up the object graphs for both kinds of windows.

    private readonly IMainWindow _mainWindow;
    private readonly ISimplifiedMainWindow _simplifiedMainWindow;

    public MainClass(
        IMainWindow mainWindow,
        ISimplifiedMainWindow simplifiedMainWindow)
    {            
        _mainWindow = mainWindow;
        _simplifiedMainWindow = simplifiedMainWindow;
    }

    public RunApp()
    { // pseudocode
        if (user is fullUser) _mainWindow.Show();
        else _simplifiedMainWindow.Show();
    }

How do I defer creation of my window objects without resorting to making an abstract factory that will basically duplicate what Castle Windsor does anyway?

reggaeguitar
  • 1,795
  • 1
  • 27
  • 48

1 Answers1

1

A factory is in fact the solution I'd recommend (and a solution I've successfully used multiple times in the past to solve this very problem).

I wouldn't implement the factory myself though, let Windsor do it (via a Typed Factory).

public interface IWindowFactory
{
   IMainWindow FullUserWindow();
   ISimplifiedMainWindow SimplifiedUserWindow();

   //optionally
   void DestroyWindow(IWindow window);
}

Now you just need to tell Windsor to build a factory for that interface

container.AddFacility<TypedFactoryFacility>();
// later on, in your installer
container.Register(Component.For<IWindowFactory>()
                      .AsFactory()
                      .LifestyleTransient());

and your app code changes to:

public RunApp()
{ // pseudocode
    if (user is fullUser) Show(factory.FullUserWindow());
    else Show(factory.SimplifiedUserWindow());
}
Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • I'm curious why you would want the factory as LifestyleTransient instead of the default singleton? – reggaeguitar Aug 27 '15 at 17:19
  • Probably at the root that makes no difference. – Krzysztof Kozmic Aug 27 '15 at 21:21
  • For any typed factory wouldn't you just want a singleton? Since Castle Windsor is generating it you shouldn't need a new instance right? It's not like the class is storing any state that you have any control over – reggaeguitar Aug 27 '15 at 21:28
  • Actually it matters if the object that 'owns' the factory is short lived. Decommissioning (destroying) a transient factory will automatically decommission objects created through it. Or in other words, it will Dispose the Disposable objects you resolve through it. But then again, it makes no difference at the root. – Krzysztof Kozmic Aug 27 '15 at 21:31