How's App to determine dependence and how to get it in MainWindow?



  • There are several heirs. Windowincluding MainWindow♪ ♪ App decide which Window I need to open it. But before that, all the dependence necessary must be created. MainWindow♪ Some of the relationships should be created App every request. For example, if MainWindow Implementation required IFooat every request, App We need to create a new facility.
    How dependency can be determined App and how to transfer them MainWindow? In doing so, only what is in WPF, i.e. without any IoC assembly, etc.



  • Resources can be used in this situation App♪ Like, there's an interface. IFoo and its implementation App♪ If a new facility is to be created every time, resources can be made available Func<IFoo>

    Model.cs

    interface IFoo {
       void Hello();
    }
    

    delegate void Log(string str);

    App.xaml.cs

    public partial class App : Application {

    class Foo : IFoo {
    public void Hello() { Console.WriteLine("hello"); }
    }

    public App() {
    // объект создается по запросу
    this.Resources.Add(typeof(IFoo), new Func<IFoo>(() => new Foo()));
    // 'ссылка' на метод Trace
    this.Resources.Add(typeof(Log), new Log(Trace));
    }

    void Trace(string str) {
    Console.WriteLine(DateTime.Now + " " + str);
    }
    }

    MainWindow.xaml.cs

    partial class MainWindow : Window {
    public MainWindow() {
    InitializeComponent();

     var f = this.Get&lt;IFoo&gt;();    // получить реализацию IFoo
     f.Hello();
     var log = this.Get&lt;Log&gt;();   // получить 'ссылку' на метод
     log("test");
    

    }
    }

    static class WindowExtensions {
    static public T Get<T>(this Window w) {
    var o = w.FindResource(typeof(T));
    return (o.GetType() == typeof(Func<T>))
    ? ((Func<T>)o)()
    : (T)o;
    }
    }

    Outcome

    hello
    1/5/2016 1:54:11 PM test




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2