Exemplo n.º 1
0
 public RestServer(ushort port)
     : base(port)
 {
     this.HttpRequestReceived += new EventHandler<HttpServerEventArgs>(RestServer_RequestReceived);
     batch = new CompositionBatch();
     batch.AddPart(this);
 }
Exemplo n.º 2
0
		protected override void Configure()
		{
			_container = new CompositionContainer(new AggregateCatalog(AssemblySource
					.Instance
					.Select(x => new AssemblyCatalog(x))
					.OfType<ComposablePartCatalog>()
				)
			);

			var batch = new CompositionBatch();
			
			_portName = SerialPort.GetPortNames()[0];
			_ecr = new Dp25(_portName);

			var messenger = new MessageAggregator();

			messenger.GetStream<SelectedPortChangedEvent>()
					.Subscribe(e => _ecr.ChangePort(e.PortName));



			batch.AddExportedValue<IWindowManager>(new WindowManager());
			batch.AddExportedValue<IMessageAggregator>(messenger);
			batch.AddExportedValue<Dp25>(_ecr);
			batch.AddExportedValue(_container);

			_container.Compose(batch);
		}
Exemplo n.º 3
0
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            //catalog.Catalogs.Add(new AssemblyCatalog(typeof(IEmailService).Assembly));

            _container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();
            batch.AddPart(this);

            #if DEBUG
            _container.Compose(batch);
            #else
            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            #endif
            return true;
        }
Exemplo n.º 4
0
        public static CompositionContainer GetMefContainer(string binDirPath, CompositionBatch batch = null, RegistrationBuilder builder = null)
        {
            if (builder == null)
                builder = new RegistrationBuilder();

            builder.ForTypesDerivedFrom<Controller>()
                            .SetCreationPolicy(CreationPolicy.NonShared).Export();

            builder.ForTypesDerivedFrom<ApiController>()
                .SetCreationPolicy(CreationPolicy.NonShared).Export();

            var catalogs = new DirectoryCatalog(binDirPath, builder);

            var container = new CompositionContainer(catalogs, CompositionOptions.DisableSilentRejection |
                                                               CompositionOptions.IsThreadSafe);

            if (batch == null)
                batch = new CompositionBatch();

            // make container availalbe for di
            batch.AddExportedValue(container);

            container.Compose(batch);

            return container;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initialises a new instance of the <see cref="MainForm"/> class.
        /// </summary>
        public MainForm()
        {
            this.InitializeComponent();

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog("..\\..\\Crypto", "*.dll"));
            var batch = new CompositionBatch();
            batch.AddPart(this);
            this.compositionContainer = new CompositionContainer(catalog);
            ////get all the exports and load them into the appropriate list tagged with the importmany
            this.compositionContainer.Compose(batch);

            this.CryptoAlgorithmComboBox.DataSource = (new List<CryptoAlgorithm> { CryptoAlgorithm.None }).Union(
                this.CryptoProviders.Select(c => c.Metadata.Algorithm).Distinct()).ToList();

            this.JoinedUsers = new BindingList<User>();

            this.ConnectedUsersDataGridView.DataSource = this.JoinedUsers;
            this.userProxy = new UserServiceClient(new InstanceContext(this));

            this.userProxy.Open();
            this.messagingProxy = new MessagingServiceClient(new InstanceContext(this));
            this.messagingProxy.Open();

            this.userProxy.Subscribe();
            foreach (var u in this.userProxy.GetJoinedUsers())
            {
                this.AddUser(u);
            }

            this.uiSyncContext = SynchronizationContext.Current;
        }
Exemplo n.º 6
0
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(IMefShapesGame).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(DefaultDimensions).Assembly));
            var partCreatorEP = new DynamicInstantiationExportProvider();

            this._container = new CompositionContainer(catalog, partCreatorEP);
            partCreatorEP.SourceProvider = this._container;

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            batch.AddExportedValue<ICompositionService>(this._container);
            batch.AddExportedValue<AggregateCatalog>(catalog);

            try
            {
                this._container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            return true;
        }
Exemplo n.º 7
0
        public static CompositionBatch BuildUpMaster(CompositionBatch batch, MasterPage master)
        {
            if (master != null)
                batch = BuildUpMaster(ComposeWebPartsUtils.BuildUp(batch, master), master.Master);

            return batch;
        }
        protected virtual void BindServices(CompositionBatch batch)
        {
            try
            {
                _tinyIoCContainer = new TinyIoCContainer();
                var eventAggregator = new EventAggregator();

                // Defaults
                batch.AddExportedValue<IWindowManager>(new WindowManager());
                batch.AddExportedValue<IEventAggregator>(eventAggregator);

                // framework and infrastructure
                _tinyIoCContainer.Register<IEventAggregator>(eventAggregator);
                // _tinyIoCContainer.Register<IServiceLocator>(new TinyServiceLocator(_container));
                _tinyIoCContainer.RegisterMultiple<IMessageEventSubscriber>(new[] {typeof (EventMessageListener)})
                    .AsSingleton();

                // register other implementations
                DependencyFactory.Configure(_tinyIoCContainer);

                // Export IoC registrations
                batch.AddExportedValue(_tinyIoCContainer.Resolve<IRestartableMessageListener>());

                batch.AddExportedValue(Container);
            }
            catch (Exception e)
            {
                Log.Error(e, "Error on Bootstrapper BindServices: {CompositionBatch}", batch);
            }
        }
        /// <summary>Override to configure the framework and setup your IoC container.</summary>
        protected override void Configure()
        {
            // Add the assembly source to the catalog.
            // ReSharper disable once RedundantEnumerableCastCall
            var catalog = new AggregateCatalog(AssemblySource.Instance.Select(i => new AssemblyCatalog(i)).OfType<ComposablePartCatalog>());

            // Create a new composition container.
            // ReSharper disable once RedundantEnumerableCastCall
            this.container = new CompositionContainer();

            // Create a new composition container.
            this.container = new CompositionContainer(catalog);

            CompositionBatch compositionBatch = new CompositionBatch();

            // Add EventAggregator to composition batch.
            compositionBatch.AddExportedValue<IEventAggregator>(new EventAggregator());
            compositionBatch.AddExportedValue<IWindowManager>(new WindowManager());
            compositionBatch.AddExportedValue<ISettingsRepository>(new SettingsRepository());
            compositionBatch.AddExportedValue<ISolutionRepository>(new SolutionRepository());
            compositionBatch.AddExportedValue(new LogWriter(this.BuildLoggingConfiguration()));

            // Add the container itself.
            compositionBatch.AddExportedValue(this.container);

            // Compose the container.
            this.container.Compose(compositionBatch);
        }
Exemplo n.º 10
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            #if (DEBUG != true)
            // Don't handle the exceptions in Debug mode because otherwise the Debugger wouldn't
            // jump into the code when an exception occurs.
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
            #endif
            XmlConfigurator.Configure();
            _log.Debug("OnStartup called");

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Controller).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(IApplicationController).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ValidationModel).Assembly));

            _container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();
            batch.AddExportedValue(_container);
            _container.Compose(batch);

            _controller = _container.GetExportedValue<IApplicationController>();
            _controller.Initialize();
            _controller.Run();
        }
Exemplo n.º 11
0
        protected override void Configure()
        {
            _container = new CompositionContainer(
                new AggregateCatalog(
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
                    )
                );

            MessageBinder.SpecialValues.Add("$orignalsourcecontext", context =>
            {
                var args = context.EventArgs as RoutedEventArgs;
                if (args == null)
                {
                    return null;
                }

                var fe = args.OriginalSource as FrameworkElement;
                if (fe == null)
                {
                    return null;
                }

                return fe.DataContext;
            });

            var batch = new CompositionBatch();

            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(_container);

            _container.Compose(batch);
        }
Exemplo n.º 12
0
        public void DualContainers()
        {
            var container1 = new CompositionContainer();
            TypeDescriptorServices dat1 = new TypeDescriptorServices();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(dat1);
            container1.Compose(batch);
            MetadataStore.AddAttribute(
                typeof(DynamicMetadataTestClass),
                ( type, attributes) => 
                    Enumerable.Concat(
                        attributes,
                        new Attribute[] { new TypeConverterAttribute(typeof(DynamicMetadataTestClassConverter)) }
                    ),
                container1
            );


            var container2 = new CompositionContainer();
            CompositionBatch batch2 = new CompositionBatch();
            TypeDescriptorServices dat2 = new TypeDescriptorServices();
            batch2.AddPart(dat2);
            container2.Compose(batch2);

            DynamicMetadataTestClass val = DynamicMetadataTestClass.Get("42");

            var attached1 = dat1.GetConverter(val.GetType());
            Assert.IsTrue(attached1.CanConvertFrom(typeof(string)), "The new type converter for DynamicMetadataTestClass should support round tripping");

            var attached2 = dat2.GetConverter(val.GetType());
            Assert.IsFalse(attached2.CanConvertFrom(typeof(string)), "The default type converter for DynamicMetadataTestClass shouldn't support round tripping");
        }
Exemplo n.º 13
0
 private void OnComponentRegistrationOnActivated(object sender, ActivatedEventArgs<object> activation_event)
 {
     // compose by batch to allow for recomposition
     var batch = new CompositionBatch();
     batch.AddPart(activation_event.Instance);
     _mefContainer.Compose(batch);
 }
Exemplo n.º 14
0
        /// <summary>
        ///     Will satisfy the imports on a object instance based on a <see cref="CompositionContainer"/>
        ///     registered with the <see cref="CompositionHost"/>. By default if no <see cref="CompositionContainer"/>
        ///     is registered the first time this is called it will be initialized to a catalog
        ///     that contains all the assemblies loaded by the initial application XAP.
        /// </summary>
        /// <param name="instance">
        ///     Object instance that contains <see cref="ImportAttribute"/>s that need to be satisfied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="instance"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="instance"/> contains <see cref="ExportAttribute"/>s applied on its type.
        /// </exception>
        /// <exception cref="ChangeRejectedException">
        ///     One or more of the imports on the object instance could not be satisfied.
        /// </exception>
        /// <exception cref="CompositionException">
        ///     One or more of the imports on the object instance caused an error while composing.
        /// </exception>
        public static void SatisfyImports(object instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var batch = new CompositionBatch();

            var attributedPart = batch.AddPart(instance);

            if (attributedPart.ExportDefinitions.Any())
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                        "Cannot call SatisfyImports on a object of type '{0}' because it is marked with one or more ExportAttributes.",
                        instance.GetType().FullName), "instance");
            }

            CompositionContainer container = null;

            // Ignoring return value because we don't need to know if we created it or not
            CompositionHost.TryGetOrCreateContainer(_createContainer, out container);

            container.Compose(batch);
        }
Exemplo n.º 15
0
        public void ComposeWithTypesExportedFromPythonAndCSharp(
            object compositionTarget,
            string scriptsToImport,
            params Type[] typesToImport)
        {
            ScriptSource script;
            var engine = Python.CreateEngine();
            using (var scriptStream = GetType().Assembly.
                GetManifestResourceStream(GetType(), scriptsToImport))
            using (var scriptText = new StreamReader(scriptStream))
            {
                script = engine.CreateScriptSourceFromString(scriptText.ReadToEnd());
            }

            var typeExtractor = new ExtractTypesFromScript(engine);
            var exports = typeExtractor.GetPartsFromScript(script, typesToImport).ToList();

            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            var container = new CompositionContainer(catalog);
            var batch = new CompositionBatch(exports, new ComposablePart[] { });
            container.Compose(batch);

            container.SatisfyImportsOnce(compositionTarget);
        }
Exemplo n.º 16
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            #if (DEBUG != true)
            // Don't handle the exceptions in Debug mode because otherwise the Debugger wouldn't
            // jump into the code when an exception occurs.
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
            #endif

            AggregateCatalog catalog = new AggregateCatalog();
            // Add the WpfApplicationFramework assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Controller).Assembly));
            // Add the Waf.BookLibrary.Library.Presentation assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            // Add the Waf.BookLibrary.Library.Applications assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShellViewModel).Assembly));

            this.container = new CompositionContainer(catalog);
            CompositionBatch batch = new CompositionBatch();
            batch.AddExportedValue(container);
            this.container.Compose(batch);

            this.applicationController = container.GetExportedValue<IApplicationController>();
            this.applicationController.Initialize();
            this.applicationController.Run();
        }
Exemplo n.º 17
0
	    protected virtual void BindServices(CompositionBatch batch)
        {
            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(Container);
	        batch.AddExportedValue(this);
        }
Exemplo n.º 18
0
        public void ConventionCatalog_should_support_type_exports()
        {
            var registry = new PartRegistry();
            registry.TypeScanner = new AssemblyTypeScanner(Assembly.GetExecutingAssembly());

            registry
                .Part()
                .ForType<SampleExport>()
                .Export();

            var catalog =
               new ConventionCatalog(registry);

            var instance =
                new ConventionPart<SampleExport>();

            var batch =
                new CompositionBatch();
            batch.AddPart(instance);

            var container =
                new CompositionContainer(catalog);

            container.Compose(batch);

            instance.Imports.Count().ShouldEqual(1);
        }
Exemplo n.º 19
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

            catalog = new AggregateCatalog();
            // Add the WpfApplicationFramework assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModel).Assembly));
            // Add the Waf.BookLibrary.Library.Presentation assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            // Add the Waf.BookLibrary.Library.Applications assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShellViewModel).Assembly));

            // Load module assemblies as well (e.g. Reporting extension). See App.config file.
            foreach(string moduleAssembly in Settings.Default.ModuleAssemblies)
            {
                catalog.Catalogs.Add(new AssemblyCatalog(moduleAssembly));
            }

            container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);
            CompositionBatch batch = new CompositionBatch();
            batch.AddExportedValue(container);
            container.Compose(batch);

            moduleControllers = container.GetExportedValues<IModuleController>();
            foreach (IModuleController moduleController in moduleControllers) { moduleController.Initialize(); }
            foreach (IModuleController moduleController in moduleControllers) { moduleController.Run(); }
        }
Exemplo n.º 20
0
        internal static IServiceLocator GetServiceLocator(Assembly assembly, CompositionBatch batch)
        {
            var assemblyLocation = assembly.Location;
            var file = new FileInfo(assemblyLocation);

            var catalogs = new List<ComposablePartCatalog>
            {
                new AssemblyCatalog(assembly),
                new DirectoryCatalog(file.DirectoryName ?? ".")
            };

            var catalog = new AggregateCatalog(catalogs);

            var container = new CompositionContainer(catalog,
                                                        CompositionOptions.DisableSilentRejection |
                                                        CompositionOptions.IsThreadSafe );

            var serviceLocator = new MefServiceLocator(container);

            batch.AddExportedValue(container);
            batch.AddExportedValue<IServiceLocator>(serviceLocator);

            container.Compose(batch);

            return serviceLocator;
        }
        public void SatisfyImportsOnce(ComposablePart part)
        {
            if (this.DoNothingOnSatisfyImportsOnce)
            {
                return;
            }

            CompositionBatch batch = new CompositionBatch();

            // We only want to include the standard exports and parts to compose in the first composition
            if (!this.alreadyComposed)
            {
                foreach (object instance in this.PartsToCompose)
                {
                    batch.AddPart(instance);
                }

                foreach (Export export in this.ExportsToCompose)
                {
                    batch.AddExport(export);
                }
            }

            if (part != null)
            {
                batch.AddPart(part);
            }

            this.container.Compose(batch);
            this.alreadyComposed = true;
        }
Exemplo n.º 22
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

#if (DEBUG != true)
            // Don't handle the exceptions in Debug mode because otherwise the Debugger wouldn't
            // jump into the code when an exception occurs.
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
#endif

            catalog = new AggregateCatalog();
            // Add the WpfApplicationFramework assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Controller).Assembly));
            // Add the Waf.BookLibrary.Library.Presentation assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            // Add the Waf.BookLibrary.Library.Applications assembly to the catalog
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShellViewModel).Assembly));

            // Load module assemblies as well (e.g. Reporting extension). See App.config file.
            foreach(string moduleAssembly in Settings.Default.ModuleAssemblies)
            {
                catalog.Catalogs.Add(new AssemblyCatalog(moduleAssembly));
            }
            
            container = new CompositionContainer(catalog);
            CompositionBatch batch = new CompositionBatch();
            batch.AddExportedValue(container);
            container.Compose(batch);

            moduleControllers = container.GetExportedValues<IModuleController>();
            foreach (IModuleController moduleController in moduleControllers) { moduleController.Initialize(); }
            foreach (IModuleController moduleController in moduleControllers) { moduleController.Run(); }
        }
Exemplo n.º 23
0
        public void SingleContainerPartReplacement()
        {
            var container = ContainerFactory.Create();
            var importPart = PartFactory.CreateImporter(true, "value1", "value2");

            CompositionBatch batch = new CompositionBatch();
            var export1Key = batch.AddExportedValue("value1", "Hello");
            batch.AddExportedValue("value2", "World");
            batch.AddPart(importPart);
            container.Compose(batch);

            Assert.AreEqual(2, importPart.ImportSatisfiedCount);
            Assert.AreEqual("Hello", importPart.GetImport("value1"));
            Assert.AreEqual("World", importPart.GetImport("value2"));

            importPart.ResetImportSatisfiedCount();

            batch = new CompositionBatch();
            batch.RemovePart(export1Key);
            batch.AddExportedValue("value1", "Goodbye");
            container.Compose(batch);

            Assert.AreEqual(1, importPart.ImportSatisfiedCount);
            Assert.AreEqual("Goodbye", importPart.GetImport("value1"));
            Assert.AreEqual("World", importPart.GetImport("value2"));
        }
Exemplo n.º 24
0
        private bool Compose()
        {
            var catalog = new System.ComponentModel.Composition.Hosting.AggregateCatalog();
            //            var catalog = new AggregatingComposablePartCatalog();
            catalog.Catalogs.Add(
                new RubyCatalog(new RubyPartFile("calculator_ops.rb")));
            catalog.Catalogs.Add(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new System.ComponentModel.Composition.Hosting.CompositionContainer(catalog);
            //_container. AddPart(this);
            var batch = new System.ComponentModel.Composition.Hosting.CompositionBatch();
            batch.AddPart(this);
            //_container.AddPart(this);
            //_container.Compose(this);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }
            return true;
        }
Exemplo n.º 25
0
        public void Compose()
        {
            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            string executionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string generatorsPath = Path.Combine(executionPath, "Generators");
            CreatePathIfRequied(generatorsPath);
            generatorsCatalog = new DirectoryCatalog(generatorsPath);

            string uiPath = Path.Combine(executionPath, "UI");
            CreatePathIfRequied(uiPath);
            UICatalog = new DirectoryCatalog(uiPath);

            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(generatorsCatalog);
            catalog.Catalogs.Add(UICatalog);

            //Set the defaults....
            CatalogExportProvider mainProvider = new CatalogExportProvider(assemblyCatalog);
            CompositionContainer container = new CompositionContainer(catalog, mainProvider);
            mainProvider.SourceProvider = container;

            var batch = new CompositionBatch();
            batch.AddPart(this);

            RefreshCatalog refreshCatalog = new RefreshCatalog(generatorsCatalog, UICatalog);
            container.ComposeParts(refreshCatalog);
            container.Compose(batch);

            Logger.Write("Compose complete");
        }
Exemplo n.º 26
0
        public Runner Init(IFeedbackProvider feedbackProvider, string[] args)
        {
            var catalog = new AggregateCatalog(new AssemblyCatalog(typeof(Bootstrapper).Assembly));

            var currentDir = Environment.CurrentDirectory;
            var assemblyDir = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath).Directory.FullName;

            var paths = new string[]
            {
                assemblyDir,
                Path.Combine(assemblyDir, "Tasks"),
                currentDir,
                Path.Combine(currentDir, "Tasks")
            }.Unique();

            var dirCatalogs = paths.Where(x => Directory.Exists(x))
                                   .Select(x => new DirectoryCatalog(x, "*.Tasks.dll"));
            dirCatalogs.Apply(x => catalog.Catalogs.Add(x));

            var container = new CompositionContainer(catalog);

            var parsed = new ArgumentParser().Parse(args);
            var runner = new Runner(parsed.ActualArgs.ToArray());

            var batch = new CompositionBatch();
            batch.AddExportedValue<IFeedbackProvider>(feedbackProvider);
            parsed.Options.Apply(x => batch.AddExportedValue<string>(x.Item1, x.Item2));
            parsed.Switches.Apply(x => batch.AddExportedValue<bool>(x, true));
            batch.AddPart(runner);
            container.Compose(batch);

            return runner;
        }
Exemplo n.º 27
0
        /// <summary>
        /// By default, we are configured to use MEF
        /// </summary>
        protected override void Configure()
        {
            // Add all assemblies to AssemblySource (using a temporary DirectoryCatalog).
            var directoryCatalog = new DirectoryCatalog(@"./");
            AssemblySource.Instance.AddRange(
                directoryCatalog.Parts
                    .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
                    .Where(assembly => !AssemblySource.Instance.Contains(assembly)));

            // Prioritise the executable assembly. This allows the client project to override exports, including IShell.
            // The client project can override SelectAssemblies to choose which assemblies are prioritised.
            var priorityAssemblies = SelectAssemblies().ToList();
            var priorityCatalog = new AggregateCatalog(priorityAssemblies.Select(x => new AssemblyCatalog(x)));
            var priorityProvider = new CatalogExportProvider(priorityCatalog);

            // Now get all other assemblies (excluding the priority assemblies).
            var mainCatalog = new AggregateCatalog(
                AssemblySource.Instance
                    .Where(assembly => !priorityAssemblies.Contains(assembly))
                    .Select(x => new AssemblyCatalog(x)));
            var mainProvider = new CatalogExportProvider(mainCatalog);

            Container = new CompositionContainer(priorityProvider, mainProvider);
            priorityProvider.SourceProvider = Container;
            mainProvider.SourceProvider = Container;

            var batch = new CompositionBatch();

            BindServices(batch);
            batch.AddExportedValue(mainCatalog);

            Container.Compose(batch);
        }
Exemplo n.º 28
0
        public void GetValuesByType()
        {
            var cat = CatalogFactory.CreateDefaultAttributed();

            var container = new CompositionContainer(cat);

            string itestName = AttributedModelServices.GetContractName(typeof(ITest));

            var e1 = container.GetExportedValues<ITest>();
            var e2 = container.GetExports<ITest, object>(itestName);

            Assert.IsInstanceOfType(e1.First(), typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e1.Skip(1).First(), typeof(T2), "Second should be T2");

            Assert.IsInstanceOfType(e2.First().Value, typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e2.Skip(1).First().Value, typeof(T2), "Second should be T2");

            CompositionContainer childContainer = new CompositionContainer(container);
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new T1());
            container.Compose(batch);
            var t1 = childContainer.GetExportedValue<ITest>();
            var t2 = childContainer.GetExport<ITest, object>(itestName);

            Assert.IsInstanceOfType(t1, typeof(T1), "First (resolved) should be T1");
            Assert.IsInstanceOfType(t2.Value, typeof(T1), "First (resolved) should be T1");
        }
Exemplo n.º 29
0
 private void Compose()
 {
     var container = new CompositionContainer(directories);
       var batch = new CompositionBatch();
       batch.AddPart(this);
       container.Compose(batch);
 }
Exemplo n.º 30
0
 public ExportProvider CreateExportProvider(CompositionBatch additionalValues) {
     var container = new CompositionContainer(_catalogLazy.Value, CompositionOptions.DisableSilentRejection);
     AddValues(container);
     container.Compose(additionalValues);
     _containers.Enqueue(container);
     return container;
 }
 public void Compose(CompositionBatch batch)
 {
     Contract.Requires(batch != null);
 }
        public void Compose(CompositionBatch batch)
        {
            this.ThrowIfDisposed();
            this.EnsureRunning();

            Requires.NotNull(batch, "batch");

            // Quick exit test can be done prior to cloning since it's just an optimization, not a
            // change in behavior
            if ((batch.PartsToAdd.Count == 0) && (batch.PartsToRemove.Count == 0))
            {
                return;
            }

            CompositionResult result = CompositionResult.SucceededResult;

            // Clone the batch, so that the external changes wouldn't happen half-way thorugh compose
            // NOTE : this does not guarantee the atomicity of cloning, which is not the goal anyway,
            // rather the fact that all subsequent calls will deal with an unchanging batch
            batch = new CompositionBatch(batch.PartsToAdd, batch.PartsToRemove);

            var newParts = GetUpdatedPartsList(batch);

            // Allow only recursive calls from the import engine to see the changes until
            // they've been verified ...
            using (var atomicComposition = new AtomicComposition())
            {
                // Don't allow reentrant calls to compose during previewing to prevent
                // corrupted state.
                if (this._currentlyComposing)
                {
                    throw new InvalidOperationException(Strings.ReentrantCompose);
                }

                this._currentlyComposing = true;

                try
                {
                    // In the meantime recursive calls need to be able to see the list as well
                    atomicComposition.SetValue(this, newParts);

                    // Recompose any existing imports effected by the these changes first so that
                    // adapters, resurrected parts, etc. can all play their role in satisfying
                    // imports for added parts
                    this.Recompose(batch, atomicComposition);

                    // Ensure that required imports can be satisfied
                    foreach (ComposablePart part in batch.PartsToAdd)
                    {
                        // collect the result of previewing all the adds in the batch
                        try
                        {
                            this._importEngine.PreviewImports(part, atomicComposition);
                        }
                        catch (ChangeRejectedException ex)
                        {
                            result = result.MergeResult(new CompositionResult(ex.Errors));
                        }
                    }

                    result.ThrowOnErrors(atomicComposition);

                    // Complete the new parts since they passed previewing.`
                    using (this._lock.LockStateForWrite())
                    {
                        this._parts = newParts;
                    }

                    atomicComposition.Complete();
                }
                finally
                {
                    this._currentlyComposing = false;
                }
            }

            // Satisfy Imports
            // - Satisfy imports on all newly added component parts
            foreach (ComposablePart part in batch.PartsToAdd)
            {
                result = result.MergeResult(CompositionServices.TryInvoke(() =>
                                                                          this._importEngine.SatisfyImports(part)));
            }

            // return errors
            result.ThrowOnErrors();
        }
        public void Compose(CompositionBatch batch)
        {
            ThrowIfDisposed();
            EnsureRunning();

            Requires.NotNull(batch, nameof(batch));

            // Quick exit test can be done prior to cloning since it's just an optimization, not a
            // change in behavior
            if ((batch.PartsToAdd.Count == 0) && (batch.PartsToRemove.Count == 0))
            {
                return;
            }

            CompositionResult result = CompositionResult.SucceededResult;

            // Get updated parts list and a cloned batch
            var newParts = GetUpdatedPartsList(ref batch);

            // Allow only recursive calls from the import engine to see the changes until
            // they've been verified ...
            using (var atomicComposition = new AtomicComposition())
            {
                // Don't allow reentrant calls to compose during previewing to prevent
                // corrupted state.
                if (_currentlyComposing)
                {
                    throw new InvalidOperationException(SR.ReentrantCompose);
                }

                _currentlyComposing = true;

                try
                {
                    // In the meantime recursive calls need to be able to see the list as well
                    atomicComposition.SetValue(this, newParts);

                    // Recompose any existing imports effected by the these changes first so that
                    // adapters, resurrected parts, etc. can all play their role in satisfying
                    // imports for added parts
                    Recompose(batch, atomicComposition);

                    // Ensure that required imports can be satisfied
                    foreach (ComposablePart part in batch.PartsToAdd)
                    {
                        // collect the result of previewing all the adds in the batch
                        try
                        {
                            ImportEngine.PreviewImports(part, atomicComposition);
                        }
                        catch (ChangeRejectedException ex)
                        {
                            result = result.MergeResult(new CompositionResult(ex.Errors));
                        }
                    }

                    result.ThrowOnErrors(atomicComposition);

                    // Complete the new parts since they passed previewing.`
                    using (_lock.LockStateForWrite())
                    {
                        _parts = newParts;
                    }

                    atomicComposition.Complete();
                }
                finally
                {
                    _currentlyComposing = false;
                }
            }

            // Satisfy Imports
            // - Satisfy imports on all newly added component parts
            foreach (ComposablePart part in batch.PartsToAdd)
            {
                result = result.MergeResult(CompositionServices.TryInvoke(() =>
                                                                          ImportEngine.SatisfyImports(part)));
            }

            // return errors
            result.ThrowOnErrors();
        }
Exemplo n.º 34
0
 private List <ComposablePart> GetUpdatedPartsList(ref CompositionBatch batch !!)
 {