Example #1
0
        static Composition()
        {
            var pluginName = ConfigSettingHelper.GetAppStr("PluginName");
            var dirCatalog = new DirectoryCatalog(".", pluginName + ".*.dll");

            container = new System.ComponentModel.Composition.Hosting.CompositionContainer(dirCatalog);
        }
Example #2
0
        public void Load(IModuleConfiguration config, string modulePackagesPath, string extension, params string[] moduleNames)
        {
            _logger.Debug("Loading modules from: " + modulePackagesPath);
            var paths = _resolver.GetAssemblyPaths(modulePackagesPath, string.Empty);
            var catalog = new AggregateCatalog();
            foreach (var path in paths)
            {
                _addToCatalog(path, catalog);
            }

            var container = new CompositionContainer(catalog);
            var lazyModules = _getModules(container);
            var modules = lazyModules
                .Where(m => moduleNames.Contains(m.Metadata.Name) ||
                    (extension != null && m.Metadata.Extensions != null && (m.Metadata.Extensions.Split(',').Contains(extension))))
                .Select(m => m.Value);

            _logger.Debug("Initializing modules");
            foreach (var module in modules)
            {
                _logger.Debug(string.Format("Initializing module:{0}", module.GetType().FullName));
                module.Initialize(config);
            }

            _logger.Debug("Modules initialized");
        }
Example #3
0
		public App()
		{
			var cmdArgs = Environment.GetCommandLineArgs().Skip(1);
			App.CommandLineArguments = new CommandLineArguments(cmdArgs);
			if (App.CommandLineArguments.SingleInstance ?? true) {
				cmdArgs = cmdArgs.Select(FullyQualifyPath);
				string message = string.Join(Environment.NewLine, cmdArgs);
				if (SendToPreviousInstance("ILSpy:\r\n" + message, !App.CommandLineArguments.NoActivate)) {
					Environment.Exit(0);
				}
			}
			InitializeComponent();
			
			var catalog = new AggregateCatalog();
			catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));
			catalog.Catalogs.Add(new DirectoryCatalog(".", "*.Plugin.dll"));
			
			compositionContainer = new CompositionContainer(catalog);
			
			Languages.Initialize(compositionContainer);
			
			if (!Debugger.IsAttached) {
				AppDomain.CurrentDomain.UnhandledException += ShowErrorBox;
				Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException;
			}
			
			EventManager.RegisterClassHandler(typeof(Window),
			                                  Hyperlink.RequestNavigateEvent,
			                                  new RequestNavigateEventHandler(Window_RequestNavigate));
		}
        public static Expression Resolve(this Expression source, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container)
        {
            if (cc == null)
            {
                cc = new CodeContext();
            }

            // It does happen that we are asked to translate a null expression. This could be a static method call, for example.

            if (source == null)
                return null;

            try
            {
                Debug.WriteLine("Expression Resolver: Resolving {0}{1}", source.ToString(), "");
                Debug.Indent();
                var r = ResolveToExpression.Translate(source, gc, cc, container);
                Debug.WriteLine("Expression Resolver: Result: {0}{1}", r == null ? "<null>" : r.ToString(), "");
                return r;
            }
            finally
            {
                Debug.Unindent();
            }
        }
Example #5
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;
        }
Example #6
0
        public void LoadPlugins(IEnumerable<ComposablePartCatalog> catalogs = null)
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));

            if (catalogs != null)
            {
                foreach (var additionalCatalog in catalogs)
                {
                    catalog.Catalogs.Add(additionalCatalog);
                }
            }

            //Create the CompositionContainer with the parts in the catalog
            Container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                Container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }
Example #7
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;
        }
Example #8
0
        /// <summary>
        /// This method loads the plugins.
        /// </summary>
        private void AssembleComponents()
        {
            var catalog = new AggregateCatalog();

            //Note: we load not only from the plugins folder, but from this assembly as well.
            var executingAssemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            if (Directory.Exists(Environment.CurrentDirectory + "\\Plugins"))
            {
                catalog.Catalogs.Add(new DirectoryCatalog("Plugins"));
            }

            catalog.Catalogs.Add(executingAssemblyCatalog);

            var container = new CompositionContainer(catalog);

            try
            {
                container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                _dialogService.ShowMessageAsync(_mainVm, "Error", string.Format("There was an error loading plugins: {0}", compositionException)).Forget();
            }
        }
Example #9
0
 public ModuleOne(IRegionManager regionManager, CompositionContainer container)
 {
     if(regionManager == null) throw new ArgumentNullException("regionManager");
     if(container == null) throw new ArgumentNullException("container");
     _regionManager = regionManager;
     _container = container;
 }
        public FileController(CompositionContainer container, IMessageService messageService, IFileDialogService fileDialogService,
            IShellService shellService, FileService fileService)
        {
            this.container = container;
            this.messageService = messageService;
            this.fileDialogService = fileDialogService;
            this.shellService = shellService;
            this.fileService = fileService;
            this.documentTypes = new List<IDocumentType>();

            this.newDocumentCommand = new DelegateCommand(NewDocumentCommand, CanNewDocumentCommand);
            this.closeDocumentCommand = new DelegateCommand(CloseDocumentCommand, CanCloseDocumentCommand);
            this.saveDocumentCommand = new DelegateCommand(SaveDocumentCommand, CanSaveDocumentCommand);
            this.saveAllDocumentCommand = new DelegateCommand(SaveAllDocumentCommand, CanSaveAllDocumentCommand);
            this.newSolutionCommand = new DelegateCommand(NewSolutionCommand);
            this.openSolutionCommand = new DelegateCommand(OpenSolutionCommand);
            this.closeSolutionCommand = new DelegateCommand(CloseSolutionCommand, CanCloseSolutionCommand);
            this.showSolutionCommand = new DelegateCommand(ShowSolutionCommand, CanShowSolutionCommand);

            this.fileService.NewDocumentCommand = this.newDocumentCommand;
            this.fileService.CloseDocumentCommand = this.closeDocumentCommand;
            this.fileService.SaveDocumentCommand = this.saveDocumentCommand;
            this.fileService.SaveAllDocumentCommand = this.saveAllDocumentCommand;
            this.fileService.NewSolutionCommand = this.newSolutionCommand;
            this.fileService.OpenSolutionCommand = this.openSolutionCommand;
            this.fileService.CloseSolutionCommand = this.closeSolutionCommand;
            this.fileService.ShowSolutionCommand = this.showSolutionCommand;

            this.recentSolutionList = Settings.Default.RecentSolutionList;
            if (this.recentSolutionList == null) { this.recentSolutionList = new RecentFileList(); }
            this.fileService.RecentSolutionList = recentSolutionList;

            AddWeakEventListener(fileService, FileServicePropertyChanged);
        }
Example #11
0
        private static IRun CreateRun()
        {
            ThreadPool.SetMinThreads(32, 32);

            var args = ParseArguments();

            var compositionContainer = new CompositionContainer(new AssemblyCatalog(typeof(Program).Assembly));

            compositionContainer.ComposeExportedValue(new RunData
            {
                SampleRate = args.SampleRate,
                Warmup = args.Warmup,
                Duration = args.Duration,
                Connections = args.Connections,
                Payload = GetPayload(args.PayloadSize),
                Senders = args.Senders,
                Transport = args.Transport,
                Host = args.Host,
                Url = args.Url,
                SendDelay = args.SendDelay,

                // Scaleout
                RedisServer = args.RedisServer,
                RedisPort = args.RedisPort,
                RedisPassword = args.RedisPassword,
                ServiceBusConnectionString = args.ServiceBusConnectionString,
                SqlConnectionString = args.SqlConnectionString,
                SqlTableCount = args.SqlTableCount,
            });

            return compositionContainer.GetExportedValue<IRun>(args.RunName);
        }
Example #12
0
        /// <summary>
        /// Default private constructor.
        /// </summary>
        private ExtensionManager()
        {
            if (!Config.DisableComposition)
            {
                // Let MEF scan for imports
                var catalog = new AggregateCatalog();

                catalog.Catalogs.Add(Config.DisableCatalogSearch ? new DirectoryCatalog("Bin", "Piranha*.dll") : new DirectoryCatalog("Bin"));

            #if !NET40
                if (!System.Web.Compilation.BuildManager.IsPrecompiledApp)
                {
            #endif
                    try
                    {
                        // This feature only exists for Web Pages
                        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.Load("App_Code")));
                    }
                    catch { }
            #if !NET40
                }
            #endif

                Container = new CompositionContainer(catalog);
                Container.ComposeParts(this);
            }
        }
 public void ComposeParts(object target)
 {
     var path = PathProvider.BinaryPath;
     var directoryCatalog = new DirectoryCatalog(path);
     var container = new CompositionContainer(directoryCatalog);
     container.ComposeParts(target);
 }
        public void Initialize()
        {
            container = new CompositionContainer(
                new AggregateCatalog(
                    new AssemblyCatalog(
                        typeof (ITypedPool).Assembly
                        ),
                    new TypeCatalog(typeof (Registrator)),
                    new TypeCatalog(typeof (ResourcePool)),
                    new TypeCatalog(typeof (NotifiedElementGetter)),
                    new TypeCatalog(typeof(NotifiedElementPoster)),
                    new TypeCatalog(typeof (UnnotifiedElementGetter)),
                    new TypeCatalog(typeof (UnnotifiedElementPoster))));
            _uplink = _mockRepository.DynamicMock<AnnouncerUplink>();
            _downlink = _mockRepository.DynamicMock<AnnouncerDownlink>();
            _downlink.Expect(k => k.Subscribe(null))
                   .IgnoreArguments()
                   .Repeat.Once();
            _downlink.Replay();

            container.ComposeExportedValue(_uplink);
            container.ComposeExportedValue(_downlink);
            //_poster = _mockRepository.DynamicMock<NotifiedElementPoster>();
            //_posterFactory = _mockRepository.DynamicMock<IPacketResourcePoster>();
        //    container.ComposeExportedValue<ResourcePoster>(_poster);
            container.ComposeExportedValue(_posterFactory);
            _pool = container.GetExportedValue<ITypedPool>();
            _subscriptor = container.GetExportedValue<IAnnouncerSubscriptor>();
            var service = container.GetExportedValue<ICacheServicing>();
            service.Initialize(new Settings
            {
                
            }, container);
        }
        public override void Invoke(CompositionContainer container)
        {
            TemplateInfo templateInfo;
            if (!this.TemplateResolver.TryResolve(this.Template, out templateInfo))
                Console.WriteLine("Template not found: '{0}'.", this.Template);

            do
            {
                foreach (string filename in templateInfo.GetFiles())
                {
                    Console.WriteLine(filename);
                    string targetPath = System.IO.Path.Combine(this.Path, filename);
                    string targetDir = System.IO.Path.GetDirectoryName(targetPath);
                    Directory.CreateDirectory(targetDir);
                    using (var target = new FileStream(targetPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                    using (var content = templateInfo.Source.OpenFile(filename, FileMode.Open))
                    {
                        content.CopyTo(target);
                        content.Close();
                        target.Close();
                    }
                }

                templateInfo = templateInfo.Inherits;
            } while (this.IncludeInherited && templateInfo != null);
        }
Example #16
0
		void LoadPlugins() {
			try{
				var pluginsPath = Utils.MapPath("~/plugins");
				if (!Directory.Exists(pluginsPath)) {
					plugins = Enumerable.Empty<IPlugin>();
					return;
				}
				var catalog = new DirectoryCatalog(pluginsPath);
				var container = new CompositionContainer(catalog);
				container.SatisfyImportsOnce(this);
			} catch (Exception err) {
				//swallow error
				log.WriteError(String.Format("error during loading plugins: {0}", err.Message));
				dbg.Break();
				plugins = Enumerable.Empty<IPlugin>();
			}
			foreach (var p in plugins) {
				try {
					p.Init();
				} catch (Exception err) {
					//swallow error
					log.WriteError(String.Format("error during plugin initialization: {0}", err.Message));
					dbg.Break();
				}
			}
		}
Example #17
0
        public void TestMefStatusReportable()
        {
            string dir = AssemblyDirectory;

            //Lets get the nlog status reportable from MEF directory..
            CompositionContainer _container;
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(TestMEF).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(AssemblyDirectory));

            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
               _container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }

            reporter.Report(2,1,"Test Report");
        }
Example #18
0
        public void Initialize()
        {
            var catalog = new AggregateCatalog();

            //Adds the program's assembly
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(PluginInfrastructre).Assembly));


            string programassembly = System.Reflection.Assembly.GetAssembly(typeof(PluginInfrastructre)).Location;

            string programpath = Path.GetDirectoryName(programassembly);

            //add the program's path
            catalog.Catalogs.Add(new DirectoryCatalog(programpath));

            _container = new CompositionContainer(catalog);

            try
            {
                //Initialize types found and assign new instances to Plugins
                Plugins = _container.GetExportedValues<IPlugin>();
                
            }
            catch (CompositionException compositionException)
            {
                throw;
            }
        }
Example #19
0
        /// <summary>
        /// Actually try and process this! The count consisits of a count integer and something to increment it
        /// at its current spot.
        /// </summary>
        /// <param name="resultOperator"></param>
        /// <param name="queryModel"></param>
        /// <param name="codeEnv"></param>
        /// <returns></returns>
        public Expression ProcessResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container)
        {
            if (gc == null)
                throw new ArgumentNullException("CodeEnv must not be null!");

            var c = resultOperator as CountResultOperator;
            if (c == null)
                throw new ArgumentNullException("resultOperator can only be a CountResultOperator and must not be null");

            //
            // The accumulator where we will store the result.
            //

            var accumulator = DeclarableParameter.CreateDeclarableParameterExpression(typeof(int));
            accumulator.SetInitialValue("0");

            //
            // Use the Aggregate infrasturcutre to do the adding. This
            // has the advantage that it will correctly combine with
            // similar statements during query optimization.
            //

            var add = Expression.Add(accumulator, Expression.Constant((int)1));
            var addResolved = ExpressionToCPP.GetExpression(add, gc, cc, container);

            gc.Add(new StatementAggregate(accumulator, addResolved));
            return accumulator;
        }
Example #20
0
 private static IList<IContentProvider> GetContentProviders(IKernel kernel)
 {
     // Use MEF to locate the content providers in this assembly
     var compositionContainer = new CompositionContainer(new AssemblyCatalog(typeof(ResourceProcessor).Assembly));
     compositionContainer.ComposeExportedValue(kernel);
     return compositionContainer.GetExportedValues<IContentProvider>().ToList();
 }
        public TestHarness(string pluginDirectoryPath, Type pluginAssemblyType, string pluginType)
        {
            var catalog = new AggregateCatalog();
            this._pluginType = pluginType;

            try
            {
                Assembly[] assemblies = new Assembly[]{ Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly(), Assembly.GetEntryAssembly() };
                foreach (Assembly assembly in assemblies)
                {
                    catalog.Catalogs.Add(new AssemblyCatalog(assembly));
                    catalog.Catalogs.Add(new DirectoryCatalog(Path.GetDirectoryName(assembly.Location)));
                }

                if (!Object.ReferenceEquals(pluginAssemblyType, null))
                {
                    catalog.Catalogs.Add(new AssemblyCatalog(pluginAssemblyType.Assembly));
                }

                if (!Object.ReferenceEquals(pluginDirectoryPath, null))
                {
                    if (Directory.Exists(pluginDirectoryPath))
                    {
                        catalog.Catalogs.Add(new DirectoryCatalog(pluginDirectoryPath));
                    }
                }

                this.container = new CompositionContainer(catalog);
                this.container.ComposeParts(this);
            }
            catch (CompositionException cex)
            {
                Console.WriteLine(cex.ToString());
            }
        }
Example #22
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;
        }
Example #23
0
		private static void ComposeConnectionFactory()
		{
			try
			{
				using (var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory))
				using (var container = new CompositionContainer(catalog))
				{
					var export = container.GetExportedValueOrDefault<IConnectionFactory>();
					if (export != null)
					{
						Factory = export;
						Console.WriteLine("Using {0}", Factory.GetType());
					}
				}
			}
			catch (ImportCardinalityMismatchException)
			{
				Console.WriteLine("More than one IConnectionFactory import was found.");
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}

			if (Factory == null)
			{
				Factory = new DefaultConnectionFactory();
				Console.WriteLine("Using default connection factory...");
			}
		}
Example #24
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");
        }
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     Container = new CompositionContainer(new DeploymentCatalog());
     CompositionHost.Initialize(Container);
     CompositionInitializer.SatisfyImports(this);
     RootVisual = new Commodities();
 }
Example #26
0
        public void DoImport()
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();

            directoryCatalog = new DirectoryCatalog(GetDirectory());
            directoryCatalog.Changing += directoryCatalog_Changing;
            directoryCatalog.Changed += directoryCatalog_Changed;

            //Adds all the parts found in all assemblies in 
            //the same directory as the executing program
            catalog.Catalogs.Add(directoryCatalog);

            //Create the CompositionContainer with the parts in the catalog
            var container = new CompositionContainer(catalog);

            try
            {
                //Fill the imports of this object
                container.ComposeParts(this);
            }
            catch (Exception ex)
            {
                Out.WriteLine("Unable to load plugins: {0}", ex.Message);
            }

        }
Example #27
0
        internal CompositionService(ComposablePartCatalog composablePartCatalog)
        {
            Assumes.NotNull(composablePartCatalog);
            this._notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged;
            try
            {
                if(this._notifyCatalog != null)
                {
                    this._notifyCatalog.Changing += this.OnCatalogChanging;
                }

                var compositionOptions = CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService;
                var compositionContainer = new CompositionContainer(composablePartCatalog, compositionOptions);
    
                this._compositionContainer = compositionContainer;
            }
            catch
            {
                if(this._notifyCatalog != null)
                {
                    this._notifyCatalog.Changing -= this.OnCatalogChanging;
                }
                throw;
            }
        }
 //Change to allow for Multi- Tenancy cases
 //User has to call this method every time he creates a new tenant DB
 public static void CreateOrUpdateUserAuthIndex(IDocumentStore store,string databaseName)
 {
     // put this index into the ravendb database
     var catalog = new CompositionContainer(new AssemblyCatalog(typeof(ServiceStack_UserAuth_ByUserNameOrEmail).Assembly));
     IndexCreation.CreateIndexes(catalog, store.DatabaseCommands.ForDatabase(databaseName), store.Conventions);
     _isInitialized = true;
 }
Example #29
0
        /// <summary>
        /// MEF Bootstrap (MEF comes from System.ComponentModel.Composition in the GAC).
        /// <para>This will return a class containing all the application's aggregate roots.</para>
        /// </summary>
        public static ComposedDemoProgram Configure(params string[] pluginDirectories)
        {
            var catalogues = 
                pluginDirectories.Select<string, ComposablePartCatalog>(d=>new DirectoryCatalog(d)).
                Concat(new []{new AssemblyCatalog(Assembly.GetExecutingAssembly())}).ToList();

            var catalog = new AggregateCatalog(catalogues);
            try
            {
                var container = new CompositionContainer(catalog);

                var composedProgram = new ComposedDemoProgram();
                container.SatisfyImportsOnce(composedProgram);

                return composedProgram;
            }
            finally
            {
                catalog.Dispose();
                foreach (var cat in catalogues)
                {
                    cat.Dispose();
                }
            }
        }
Example #30
0
    static async Task AsyncMain()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new DirectoryCatalog("."));

        CompositionContainer compositionContainer = new CompositionContainer(catalog);

        Console.Title = "Samples.MefExtensionEndpoint";
        LogManager.Use<DefaultFactory>().Level(LogLevel.Info);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.MefExtensionEndpoint");
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();
        await RunCustomizeConfiguration(compositionContainer, endpointConfiguration);
        await RunBeforeEndpointStart(compositionContainer);
        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);
        await RunAfterEndpointStart(compositionContainer, endpoint);
        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await RunBeforeEndpointStop(compositionContainer, endpoint);
            await endpoint.Stop();
        }
        await RunAfterEndpointStop(compositionContainer);
    }
Example #31
0
 public FilterContext(ObjectCache cache, CompositionContainer container, IAssetResolver assetResolver, FilterState state)
 {
     this.Container = container;
     this.Cache = cache;
     this.AssetResolver = assetResolver;
     this.State = state;
 }
Example #32
0
 /// <summary>
 /// Expressions that are actually code are left alone at the early stage.
 /// </summary>
 /// <param name="expr"></param>
 /// <param name="gc"></param>
 /// <param name="context"></param>
 /// <param name="container"></param>
 /// <returns></returns>
 public Expression ProcessMethodCall(MethodCallExpression expr, IGeneratedQueryCode gc, ICodeContext context, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     return(expr);
 }
            public CompositionServiceShim(CompositionContainer innerContainer)
            {
                ArgumentNullException.ThrowIfNull(innerContainer);

                _innerContainer = innerContainer;
            }
Example #34
0
 /// <summary>
 /// This should never ever happen - there is no such thing as passing over a
 /// constant reference of one of these guys!
 /// </summary>
 /// <param name="expr"></param>
 /// <param name="codeEnv"></param>
 /// <param name="context"></param>
 /// <param name="container"></param>
 /// <returns></returns>
 public IValue ProcessConstantReference(ConstantExpression expr, IGeneratedQueryCode codeEnv, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     throw new NotImplementedException();
 }
        internal static bool TryGetOrCreateContainer(Func <CompositionContainer> createContainer, out CompositionContainer globalContainer)
        {
            bool alreadyCreated = true;

            if (_container == null)
            {
                var container = createContainer.Invoke();
                lock (_lockObject)
                {
                    if (_container == null)
                    {
                        Thread.MemoryBarrier();
                        _container     = container;
                        alreadyCreated = false;
                    }
                }
            }
            globalContainer = _container;
            return(alreadyCreated);
        }
Example #36
0
 /// <summary>
 /// These are static classes as far as we are concerned - so they should never be able to run.
 /// </summary>
 /// <param name="expression"></param>
 /// <param name="result"></param>
 /// <param name="gc"></param>
 /// <param name="context"></param>
 /// <param name="container"></param>
 /// <returns></returns>
 public System.Linq.Expressions.Expression ProcessNew(System.Linq.Expressions.NewExpression expression, out IValue result, IGeneratedQueryCode gc, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     throw new NotImplementedException();
 }
Example #37
0
 /// <summary>
 /// Nothing like this sort of class should appear as a constant reference - so bomb if we see it.
 /// </summary>
 /// <param name="expr"></param>
 /// <param name="codeEnv"></param>
 /// <param name="context"></param>
 /// <param name="container"></param>
 /// <returns></returns>
 public Expression ProcessConstantReferenceExpression(ConstantExpression expr, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     throw new NotImplementedException();
 }
 public static void Initialize(CompositionContainer container)
 {
 }
Example #39
0
 public IValue ProcessMemberReference(MemberExpression expr, IGeneratedQueryCode gc, ICodeContext cc, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     throw new NotImplementedException();
 }
Example #40
0
 public static void SetupTestGlobalContainer(CompositionContainer container)
 {
     CompositionHost._container = null;
     CompositionHost.Initialize(container);
 }
 public CompositionServiceShim(CompositionContainer innerContainer)
 {
     Assumes.NotNull(innerContainer);
     this._innerContainer = innerContainer;
 }
Example #42
0
 public IValue CodeMethodCall(MethodCallExpression expr, IGeneratedQueryCode gc, System.ComponentModel.Composition.Hosting.CompositionContainer container)
 {
     return(new Variables.ValSimple("1", typeof(int)));
 }
Example #43
0
        internal static bool TryGetOrCreateContainer(Func <CompositionContainer> createContainer, out CompositionContainer globalContainer)
        {
            bool container = true;

            if (_container == null)
            {
                CompositionContainer compositionContainer = createContainer();
                lock (_lockObject)
                {
                    if (_container == null)
                    {
                        Thread.MemoryBarrier();
                        _container = compositionContainer;
                        container  = false;
                    }
                }
            }

            globalContainer = _container;

            return(container);
        }