Blog Archive

Monday, September 1, 2014

MEF Injects UserControls, Property and Method as Action, Func

(1) [ImportMany] handles 0 matching [Export] without blow up
(2) container.GetExportedValueOrDefault trigger IoC DI for Extensions Class
(3) IPartImportsSatisfiedNotification delay  construction of property after Ctor.
(4) Obs showed that realtime changes are injected as well.

    public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            AggregateCatalog aCat = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                new DirectoryCatalog(@".\Execution")
                );
            var container = new CompositionContainer(aCat);
            Window w = container.GetExportedValueOrDefault();
            w.Show();
        } 
    }

    [Export(typeof(Window))]
    public partial class MainWindow : Window, IPartImportsSatisfiedNotification
    {

        [ImportMany("ListUC",typeof(FrameworkElement))]
        IEnumerable controls { get; set; }

        [ImportMany("WinStyle", typeof(WindowStyle))]
        WindowStyle[] WinStyles { get; set; }

        [ImportMany("SetWinStyle", typeof(Action))]
        Action[] WinStyleActions { get; set; }
      
        public void OnImportsSatisfied()
        {
            List l = new List(controls);
            list.ItemsSource = l; // Xaml code inject a list of UC Controls 
            if (WinStyles.Length > 0)
                WindowStyle = WinStyles[0];
            if(WinStyleActions.Length>0)
            WinStyleActions[0](this);
        }
    }


    public class MyExtensions
    {
       [Export("WinStyle", typeof(WindowStyle))]
        public WindowStyle WindS
        {

            get { return WindowStyle.None; }
        }
     
        [Export("SetWinStyle")]
       public void SetWinStyle(Window w)
       {
           MessageBox.Show(this.ToString());
            Observable.Interval(TimeSpan.FromSeconds(3)).SubscribeOn(SynchronizationContext.Current).Subscribe((s) =>
             {
                 w.Dispatcher.Invoke(new Action(() =>
                 {
                     w.WindowStyle = w.WindowStyle == WindowStyle.ThreeDBorderWindow ? WindowStyle.None : WindowStyle.ThreeDBorderWindow;
                 }));
             });
           
       }
    }


  [Export("ListUC",typeof(FrameworkElement))]
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
    }

No comments: