Exemplo n.º 1
0
        private Document CreateDocument(IParameter[] parameters, string rewrittenScriptCode, ScriptingOptions Options)
        {
            var compositionContext = new System.Composition.Hosting.ContainerConfiguration()
                                     .WithAssemblies(MefHostServices.DefaultAssemblies.Concat(new[] {
                Assembly.Load("Microsoft.CodeAnalysis.Features"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features")
            }))
                                     .CreateContainer();

            var workspace = new AdhocWorkspace(MefHostServices.Create(compositionContext));

            var metadataReferences = Options
                                     .References
                                     .Select(x => x.Location)
                                     .Select(x => MetadataReference.CreateFromFile(x))
                                     .ToArray();

            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                usings: Options.Imports,
                optimizationLevel: (Debugger.IsAttached) ? OptimizationLevel.Debug : OptimizationLevel.Release);


            Solution solution = workspace.CurrentSolution;
            var      project  = solution.AddProject("SCRIPT-PROJECT", "SCRIPT-ASSEMBLY", LanguageNames.CSharp)
                                .WithParseOptions(new CSharpParseOptions(kind: Microsoft.CodeAnalysis.SourceCodeKind.Script))
                                .WithMetadataReferences(metadataReferences)
                                .WithCompilationOptions(compilationOptions);

            Document document = project.AddDocument("SCRIPT-TEMP-DOCUMENT.cs", rewrittenScriptCode);

            return(document);
        }
Exemplo n.º 2
0
        public IServiceProvider GetServiceProvider()
        {
            if (_serviceProvider != null)
            {
                return(_serviceProvider);
            }

            var container = new System.Composition.Hosting.ContainerConfiguration().WithAssembly(typeof(ScriptEditorEngine).Assembly);

            _serviceProvider = container.CreateContainer().GetExport <IServiceProvider>();
            return(_serviceProvider);
        }
Exemplo n.º 3
0
        static public void Main(string[] args)
        {
            var _benchmark = new Benchmark(() => new Action(() => new Calculator()));

            _benchmark.Add("SimpleInjector", () =>
            {
                var _container = new SimpleInjector.Container();
                _container.Register <ICalculator, Calculator>(SimpleInjector.Lifestyle.Transient);
                return(() => _container.GetInstance <ICalculator>());
            });
            //TODO : change to test new Puresharp DI recast
            _benchmark.Add("Puresharp", () =>
            {
                var _container = new Puresharp.Composition.Container();
                _container.Add <ICalculator>(() => new Calculator(), Puresharp.Composition.Lifetime.Volatile);
                return(() => _container.Enumerable <ICalculator>());
            });
            //TODO : change to test MEF2
            _benchmark.Add("MEF", () =>
            {
                var _container = new System.Composition.Hosting.ContainerConfiguration().WithAssembly(typeof(ICalculator).Assembly).CreateContainer();
                return(() => _container.GetExport <ICalculator>());
            });
            _benchmark.Add("Castle Windsor", () =>
            {
                var _container = new WindsorContainer();
                _container.Register(Castle.MicroKernel.Registration.Component.For <ICalculator>().ImplementedBy <Calculator>());
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Unity", () =>
            {
                var _container = new UnityContainer();
                _container.RegisterType <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("StuctureMap", () =>
            {
                var _container = new StructureMap.Container(_Builder => _Builder.For <ICalculator>().Use <Calculator>());
                return(() => _container.GetInstance <ICalculator>());
            });
            _benchmark.Add("DryIoc", () =>
            {
                var _container = new DryIoc.Container();
                _container.Register <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Autofac", () =>
            {
                var _builder = new Autofac.ContainerBuilder();
                _builder.RegisterType <Calculator>().As <ICalculator>();
                var _container = _builder.Build(Autofac.Builder.ContainerBuildOptions.None);
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Ninject", () =>
            {
                var _container = new Ninject.StandardKernel();
                _container.Bind <ICalculator>().To <Calculator>();
                return(() => _container.Get <ICalculator>());
            });
            _benchmark.Add("Abioc", () =>
            {
                var _setup = new Abioc.Registration.RegistrationSetup();
                _setup.Register <ICalculator, Calculator>();
                var _container = Abioc.ContainerConstruction.Construct(_setup, typeof(ICalculator).Assembly);
                return(() => _container.GetService <ICalculator>());
            });
            _benchmark.Add("Grace", () =>
            {
                var _container = new Grace.DependencyInjection.DependencyInjectionContainer();
                _container.Configure(c => c.Export <Calculator>().As <ICalculator>());
                return(() => _container.Locate <ICalculator>());
            });
            _benchmark.Run(Console.WriteLine);
        }
Exemplo n.º 4
0
        private static void Main(string[] args)
        {
            #region MEF1

            System.ComponentModel.Composition.Hosting.AggregateCatalog aggregateCatalog = new System.ComponentModel.Composition.Hosting.AggregateCatalog();
            aggregateCatalog.Catalogs.Add(new System.ComponentModel.Composition.Hosting.AssemblyCatalog(typeof(Program).Assembly));
            System.ComponentModel.Composition.Hosting.CompositionContainer compositionContainer = new System.ComponentModel.Composition.Hosting.CompositionContainer(aggregateCatalog);

            {
                ClassA classA = compositionContainer.GetExportedValue <ClassA>();
                classA.Log();
                classA.ClassB.Value.Log();
                classA.ClassB.Value.Log();
            }

            {
                ClassA classA = compositionContainer.GetExportedValue <ClassA>();
                classA.Log();
                classA.ClassB.Value.Log();
                classA.ClassB.Value.Log();
            }

            {
                ClassB classB = compositionContainer.GetExportedValue <ClassB>();
                classB.Log();
                classB.ClassA.Value.Log();
                classB.ClassA.Value.Log();
            }

            {
                ClassB classB = compositionContainer.GetExportedValue <ClassB>();
                classB.Log();
                classB.ClassA.Value.Log();
                classB.ClassA.Value.Log();
            }

            #endregion

            #region MEF2

            System.Composition.Hosting.ContainerConfiguration containerConfiguration = new System.Composition.Hosting.ContainerConfiguration().WithAssembly(typeof(Program).Assembly);
            System.Composition.Hosting.CompositionHost        compositionHost        = containerConfiguration.CreateContainer();

            {
                ClassA classA = compositionHost.GetExport <ClassA>();
                classA.Log();
                classA.ClassB.Value.Log();
                classA.ClassB.Value.Log();
            }

            {
                ClassA classA = compositionHost.GetExport <ClassA>();
                classA.Log();
                classA.ClassB.Value.Log();
                classA.ClassB.Value.Log();
            }

            {
                ClassB classB = compositionHost.GetExport <ClassB>();
                classB.Log();
                classB.ClassA.Value.Log();
                classB.ClassA.Value.Log();
            }

            {
                ClassB classB = compositionHost.GetExport <ClassB>();
                classB.Log();
                classB.ClassA.Value.Log();
                classB.ClassA.Value.Log();
            }

            #endregion
        }
Exemplo n.º 5
0
        public App()
        {
            Configuration config1   = null;
            string        directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            if (Directory.Exists(directory))
            {
                string filename = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config", SearchOption.TopDirectoryOnly) where filename.Equals(Path.GetFileNameWithoutExtension(s)) select s)
                {
                    ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();

                    exeConfigurationFileMap.ExeConfigFilename = s;
                    config1 = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                }
            }

            if (config1 == null)
            {
                config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                if (config1.AppSettings.Settings["Scripts"] != null)
                {
                    ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                    List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                    foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value) ? config1.AppSettings.Settings["Scripts"].Value : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                            }
                    }

                    Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                }

                if (config1.AppSettings.Settings["Extensions"] != null)
                {
                    List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>();

                    foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Extensions"].Value) ? config1.AppSettings.Settings["Extensions"].Value : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly))
                    {
                        assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename));
                    }

                    if (assemblyList.Count > 0)
                    {
                        using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer())
                        {
                            this.Extensions = container.GetExports <IExtension>();
                        }

                        Script.Instance.Start += new EventHandler <EventArgs>(delegate
                        {
                            foreach (IExtension extension in this.Extensions)
                            {
                                extension.Attach();
                            }
                        });
                        Script.Instance.Stop += new EventHandler <EventArgs>(delegate
                        {
                            foreach (IExtension extension in this.Extensions)
                            {
                                extension.Detach();
                            }
                        });
                    }
                }
            }
            else
            {
                Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                if (config1.AppSettings.Settings["Scripts"] == null)
                {
                    if (config2.AppSettings.Settings["Scripts"] != null)
                    {
                        if (Path.IsPathRooted(config2.AppSettings.Settings["Scripts"].Value))
                        {
                            ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                            List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                            foreach (string filename in Directory.EnumerateFiles(config2.AppSettings.Settings["Scripts"].Value, "*.csx", SearchOption.TopDirectoryOnly))
                            {
                                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                                    using (StreamReader sr = new StreamReader(fs))
                                    {
                                        taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                                    }
                            }

                            Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                        }
                        else
                        {
                            string        path          = Path.Combine(directory, config2.AppSettings.Settings["Scripts"].Value);
                            ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                            List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                            foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config2.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                            {
                                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                                    using (StreamReader sr = new StreamReader(fs))
                                    {
                                        taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                                    }
                            }

                            Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                        }
                    }
                }
                else if (Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value))
                {
                    ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                    List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                    foreach (string filename in Directory.EnumerateFiles(config1.AppSettings.Settings["Scripts"].Value, "*.csx", SearchOption.TopDirectoryOnly))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                            }
                    }

                    Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                }
                else
                {
                    string        path          = Path.Combine(directory, config1.AppSettings.Settings["Scripts"].Value);
                    ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                    List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                    foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                            }
                    }

                    Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                }

                if (config1.AppSettings.Settings["Extensions"] == null)
                {
                    if (config2.AppSettings.Settings["Extensions"] != null)
                    {
                        List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>();

                        if (Path.IsPathRooted(config2.AppSettings.Settings["Extensions"].Value))
                        {
                            foreach (string filename in Directory.EnumerateFiles(config2.AppSettings.Settings["Extensions"].Value, "*.dll", SearchOption.TopDirectoryOnly))
                            {
                                assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename));
                            }
                        }
                        else
                        {
                            string path = Path.Combine(directory, config2.AppSettings.Settings["Extensions"].Value);

                            foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config2.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly))
                            {
                                assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename));
                            }
                        }

                        if (assemblyList.Count > 0)
                        {
                            using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer())
                            {
                                this.Extensions = container.GetExports <IExtension>();
                            }

                            Script.Instance.Start += new EventHandler <EventArgs>(delegate
                            {
                                foreach (IExtension extension in this.Extensions)
                                {
                                    extension.Attach();
                                }
                            });
                            Script.Instance.Stop += new EventHandler <EventArgs>(delegate
                            {
                                foreach (IExtension extension in this.Extensions)
                                {
                                    extension.Detach();
                                }
                            });
                        }
                    }
                }
                else
                {
                    List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>();

                    if (Path.IsPathRooted(config1.AppSettings.Settings["Extensions"].Value))
                    {
                        foreach (string filename in Directory.EnumerateFiles(config1.AppSettings.Settings["Extensions"].Value, "*.dll", SearchOption.TopDirectoryOnly))
                        {
                            assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename));
                        }
                    }
                    else
                    {
                        string path = Path.Combine(directory, config1.AppSettings.Settings["Extensions"].Value);

                        foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly))
                        {
                            assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename));
                        }
                    }

                    if (assemblyList.Count > 0)
                    {
                        using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer())
                        {
                            this.Extensions = container.GetExports <IExtension>();
                        }

                        Script.Instance.Start += new EventHandler <EventArgs>(delegate
                        {
                            foreach (IExtension extension in this.Extensions)
                            {
                                extension.Attach();
                            }
                        });
                        Script.Instance.Stop += new EventHandler <EventArgs>(delegate
                        {
                            foreach (IExtension extension in this.Extensions)
                            {
                                extension.Detach();
                            }
                        });
                    }
                }
            }
        }