Exemplo n.º 1
0
        /// <summary>
        /// Registers the conventions.
        /// </summary>
        /// <param name="builder">The registration builder.</param>
        public void RegisterConventions(ConventionBuilder builder)
        {
            builder
                .ForTypesDerivedFrom<IGameManager>()
                .Export(b => b.AsContractType<IGameManager>())
                .Shared(ScopeNames.User);

            builder
                .ForTypesDerivedFrom<IUser>()
                .Export(b => b.AsContractType<IUser>())
                .Shared(ScopeNames.User);
        }
        private static AttributedModelProvider DefineConventions()
        {
            var rb = new ConventionBuilder();

            rb.ForTypesDerivedFrom<IController>().Export();

            rb.ForTypesDerivedFrom<IHttpController>().Export();

            rb.ForTypesMatching(IsAPart)
                .Export()
                .ExportInterfaces();

            return rb;
        }
Exemplo n.º 3
0
        public void MapType_OverridingSelectionOfConventionSelectedConstructor()
        {
            var builder = new ConventionBuilder();

            builder.
                ForTypesDerivedFrom<IFoo>().
                Export<IFoo>();

            builder.ForType<FooImplWithConstructors>()
                .SelectConstructor(cis => cis.ElementAtOrDefault(1));

            var fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo();

            var constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single();
            var constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single();
            var constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single();


            // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
            Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count());
            Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count());

            var ci = constructor2;
            var attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci);
            Assert.Equal(1, attrs.Count());
            Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType());
        }
Exemplo n.º 4
0
        public static void ConfigureContainer()
        {
            var containerConventions = new ConventionBuilder();

            containerConventions.ForType<DbProductRepository>()
                .ExportInterfaces()
                .SelectConstructorWithMostParameters()
                .InstancePerHttpRequest();

            containerConventions.ForType<DbLogger>()
                .ExportInterfaces()
                .SelectConstructorWithMostParameters()
                .InstancePerHttpRequest();

            containerConventions.ForType<ProductDbContext>()
                .Export()
                .InstancePerHttpRequest();

            containerConventions.ForTypesDerivedFrom<Controller>()
                .Export<IController>()
                .Export()
                .SelectConstructorWithMostParameters();

            var containerConfig = new ContainerConfiguration();
            containerConfig.WithAssembly(Assembly.GetExecutingAssembly(), containerConventions);

            containerConfig.CreateContainer().UseWithMvc();
        }
        private ConventionBuilder GetExportBuilder()
        {
            // Define exports as matching a parent type, export as that parent type
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom(contractType).Export(exportConventionBuilder => exportConventionBuilder.AsContractType(contractType));
            return(builder);
        }
Exemplo n.º 6
0
        static partial void AddUISpecificConventions( ConventionBuilder builder )
        {
            var viewModel = new ViewModelSpecification();

            builder.ForTypesDerivedFrom<IShellView>().Export().Export<IShellView>().Shared();
            builder.ForTypesMatching( viewModel.IsSatisfiedBy ).Export();
            builder.ForType<EventBroker>().Export<IEventBroker>().Shared();
        }
Exemplo n.º 7
0
        public static ConventionBuilder NewParentConventions(bool isShared)
        {
            ConventionBuilder conventions = new ConventionBuilder();

            if (isShared)
            {
                conventions.ForTypesDerivedFrom(typeof(IParent))
                .Export()
                .Shared();
            }
            else
            {
                conventions.ForTypesDerivedFrom(typeof(IParent))
                .Export();
            }
            return(conventions);
        }
Exemplo n.º 8
0
        public static async Task InitializeGeneratorsAsync(bool writeOutputMessages = false)
        {
            Current.Clear();

            Debug.WriteLine($@"Scanning local directory for OutputExecutor libraries");

            var assemblies = new List <Assembly>();

            foreach (var file in Directory.EnumerateFiles(Environment.CurrentDirectory, "*" + GenesisDefaults.LibraryExtension, SearchOption.TopDirectoryOnly))
            {
                assemblies.Add(Assembly.LoadFile(file)); //doesn't seem to mind loading everything... for now
            }
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IGeneralExecutor>()
            .Export <IGeneralExecutor>()
            .Shared();

            var configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            using var container = configuration.CreateContainer();

            var generators = container.GetExports <IGeneralExecutor>();

            Current.Clear();

            foreach (var generator in generators)
            {
                Current.Add(generator);

                try
                {
                    await generator.Initialize();

                    if (!writeOutputMessages)
                    {
                        continue;
                    }

                    Text.White($"'"); Text.Green(generator.CommandText); Text.White("' ("); Text.Cyan(generator.FriendlyName); Text.White(") was found in '"); Text.Blue(generator.GetType().Name); Text.White("'... ");
                    Text.GreenLine("OK");

                    Console.ResetColor();
                }
                catch (Exception exc)
                {
                    if (!writeOutputMessages)
                    {
                        continue;
                    }

                    Text.CliCommand(generator.CommandText); Text.White(": ");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(exc.Message);
                    Console.ResetColor();
                }
            }
        }
Exemplo n.º 9
0
        public void AsContractName_AndContractType_SetsContractNameAndType()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export((e) => e.AsContractName("hey").AsContractType(typeof(IFoo)));

            ExportAttribute exportAtt = GetExportAttribute(builder);
            Assert.Equal("hey", exportAtt.ContractName);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
        }
Exemplo n.º 10
0
        public void AsContractTypeOfT_SetsContractType()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export((e) => e.AsContractType<IFoo>());

            ExportAttribute exportAtt = GetExportAttribute(builder);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
            Assert.Null(exportAtt.ContractName);
        }
Exemplo n.º 11
0
        private static ConventionBuilder GetConventions()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IBinarySkimmer>()
            .Export <IBinarySkimmer>();

            return(conventions);
        }
Exemplo n.º 12
0
        private static ConventionBuilder GetConventions <T>()
        {
            var conventions = new ConventionBuilder();

            // New per-analyzer options mechanism
            conventions.ForTypesDerivedFrom <T>()
            .Export <T>();

            return(conventions);
        }
        internal async Task <bool> LoadCommandsAsync <T>() where T : IShellCommand
        {
            if (!Directory.Exists(Constants.COMMANDS_PATH))
            {
                Directory.CreateDirectory(Constants.COMMANDS_PATH);
            }

            AssemblyCollection?.Clear();
            AssemblyCollection = LoadAssemblies();

            if (AssemblyCollection == null || AssemblyCollection.Count <= 0)
            {
                Logger.Trace("No command assemblies found.");
                return(false);
            }

            await LoadSync.WaitAsync().ConfigureAwait(false);

            try {
                ConventionBuilder conventions = new ConventionBuilder();
                conventions.ForTypesDerivedFrom <T>().Export <T>();
                ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(AssemblyCollection, conventions);

                using CompositionHost container = configuration.CreateContainer();
                List <T> list = container.GetExports <T>().ToList();

                if (list.Count <= 0)
                {
                    return(false);
                }

                foreach (T command in list)
                {
                    if (await IsExistingCommand <T>(command.UniqueId).ConfigureAwait(false))
                    {
                        Logger.Warning($"'{command.CommandName}' shell command already exists. skipping...");
                        continue;
                    }

                    await command.InitAsync().ConfigureAwait(false);

                    Interpreter.Commands.Add(command.CommandKey, command);
                    Logger.Info($"Loaded external shell command -> {command.CommandName}");
                }

                return(true);
            }
            catch (Exception e) {
                Logger.Exception(e);
                return(false);
            }
            finally {
                LoadSync.Release();
            }
        }
Exemplo n.º 14
0
        private static AttributedModelProvider RegisterExports()
        {
            var builder = new ConventionBuilder();
            //builder.ForType<learner>().Export<learner>();
            //builder.ForTypesMatching
            //    (x => x.GetProperty("SourceMaterial") != null).Export<exam>();

            builder.ForTypesDerivedFrom<IJob>().Export<IJob>();

            return builder;
        }
Exemplo n.º 15
0
        public void AsContractName_AndContractType_ComputeContractNameFromType()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <IFoo>().Export(e => e.AsContractName(t => "Contract:" + t.FullName).AsContractType <IFoo>());

            ExportAttribute exportAtt = GetExportAttribute(builder);

            Assert.Equal("Contract:" + typeof(FooImpl).FullName, exportAtt.ContractName);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
        }
Exemplo n.º 16
0
        public void AsContractName_AndContractType_SetsContractNameAndType()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <IFoo>().Export((e) => e.AsContractName("hey").AsContractType(typeof(IFoo)));

            ExportAttribute exportAtt = GetExportAttribute(builder);

            Assert.Equal("hey", exportAtt.ContractName);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
        }
Exemplo n.º 17
0
        internal static ServiceConfigurations Find(Configuration config, ILogger logger)
        {
            logger.Information("Loading configuration", PluginDir);

            var configurations = new ServiceConfigurations(logger);

            AddInternalConfigurations();
            AddExternalPlugins();
            return(configurations);

            void AddInternalConfigurations()
            {
                logger.Information("Loading internal service configuration", PluginDir);

                var loader  = Factory.CreateLoader(config, logger).Result;
                var addData = new SetData(loader, logger);

                configurations.Add(new Singletons());
                configurations.Add(addData);
                if (config.EnablePrometheusMonitoring)
                {
                    configurations.Add(new ServiceConfiguration.Prometheus());
                }
                configurations.Add(new HealthCheck(addData, config.EnablePrometheusMonitoring));
                configurations.Add(new Swagger());
                configurations.Add(new ExceptionHandler());
            }

            void AddExternalPlugins()
            {
                if (!config.EnableCustomPlugins)
                {
                    return;
                }

                try
                {
                    logger.Information("Loading external plugins from {path}", PluginDir);
                    var conventions = new ConventionBuilder();
                    conventions.ForTypesDerivedFrom <IPlugin>().Export <IPlugin>().Shared();

                    var containerConfig = new ContainerConfiguration().WithAssembliesInPath(PluginDir, conventions);

                    using var container = containerConfig.CreateContainer();

                    var externalPlugins = container.GetExports <IPlugin>();
                    configurations.AddRange(externalPlugins);
                }
                catch (Exception e)
                {
                    logger.Warning(e, "Error loading plugins from {path}", PluginDir);
                }
            }
        }
Exemplo n.º 18
0
        private void Configure(string path)
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IContextResolver>()
            .Export <IContextResolver>()
            .Shared();

            Configuration = new ContainerConfiguration()
                            .WithAssembliesInPath(path, conventions);
        }
Exemplo n.º 19
0
        public void AsContractTypeOfT_SetsContractType()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <IFoo>().Export((e) => e.AsContractType <IFoo>());

            ExportAttribute exportAtt = GetExportAttribute(builder);

            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
            Assert.Null(exportAtt.ContractName);
        }
Exemplo n.º 20
0
            internal MefContainer(IEnumerable <Assembly> assemblies)
            {
                var conventionBuilder = new ConventionBuilder();

                conventionBuilder.ForTypesDerivedFrom <TAbstractContract>().Export <TContract>();

                this._container = new ContainerConfiguration()
                                  .WithAssemblies(assemblies, conventionBuilder)
                                  .CreateContainer();
                this._exported = this._container.GetExports <ExportFactory <TContract, TTranscription> >();
            }
Exemplo n.º 21
0
        public void AddMetadataFuncVal_AddsExportMetadataAttribute()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <IFoo>().Export(e => e.AddMetadata("name", t => t.Name));

            ExportMetadataAttribute exportAtt = GetExportMetadataAttribute(builder);

            Assert.Equal("name", exportAtt.Name);
            Assert.Equal(typeof(FooImpl).Name, exportAtt.Value);
        }
Exemplo n.º 22
0
        public void AddMetadata_AddsExportMetadataAttribute()
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <IFoo>().Export(e => e.AddMetadata("name", "val"));

            ExportMetadataAttribute exportAtt = GetExportMetadataAttribute(builder);

            Assert.Equal("name", exportAtt.Name);
            Assert.Equal("val", exportAtt.Value);
        }
Exemplo n.º 23
0
        public async Task <bool> LoadAsync()
        {
            AssemblyCollection?.Clear();
            AssemblyCollection = LoadAssemblies();

            if (AssemblyCollection == null || AssemblyCollection.Count <= 0)
            {
                Logger.Trace("No assemblies found.");
                return(false);
            }

            await ModuleLoaderSemaphore.WaitAsync().ConfigureAwait(false);

            try {
                ConventionBuilder conventions = new ConventionBuilder();
                conventions.ForTypesDerivedFrom <IModuleBase>().Export <IModuleBase>();
                ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(AssemblyCollection, conventions);

                using CompositionHost container = configuration.CreateContainer();
                List <IModuleBase> list = container.GetExports <IModuleBase>().ToList();

                if (list.Count > 0)
                {
                    foreach (IModuleBase bot in list)
                    {
                        Logger.Trace($"Loading module of type {ParseModuleType(bot.ModuleType)} ...");
                        bot.ModuleIdentifier = GenerateModuleIdentifier();
                        ModuleInfo <IModuleBase> data = new ModuleInfo <IModuleBase>(bot.ModuleIdentifier, ParseModuleType(bot.ModuleType), true)
                        {
                            Module = bot
                        };

                        Logger.Trace($"Successfully loaded module with id {bot.ModuleIdentifier} of type {data.ModuleType.ToString()}");

                        if (Modules.Count > 0 && !Modules.Contains(bot))
                        {
                            Modules.Add(bot);
                        }

                        ModulesCache.Add(data);
                    }
                }
            }
            catch (Exception e) {
                Logger.Exception(e);
                return(false);
            }
            finally {
                ModuleLoaderSemaphore.Release();
            }

            return(true);
        }
Exemplo n.º 24
0
 static void DefineFormatConventions(ConventionBuilder conventions)
 {
     conventions
     .ForTypesDerivedFrom <IFormat>()
     .Export <IFormat>(
         export => export
         .AddMetadata("Name", t => t.FullName)
         .AddMetadata("Type", t => t))
     .SelectConstructor(ctors =>
                        ctors.OrderBy(ctor => ctor.GetParameters().Length)
                        .First());
 }
Exemplo n.º 25
0
        private static AttributedModelProvider RegisterExports()
        {
            var builder = new ConventionBuilder();

            //builder.ForType<learner>().Export<learner>();
            //builder.ForTypesMatching
            //    (x => x.GetProperty("SourceMaterial") != null).Export<exam>();

            builder.ForTypesDerivedFrom <IJob>().Export <IJob>();

            return(builder);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Static helper method Exports the <paramref name="exportType"/> on the given
        /// <paramref name="conventions"/>; applying
        /// <see cref="ConventionBuilder.ForTypesDerivedFrom"/>,
        /// <see cref="ConventionBuilder.ForType"/>, or both according to
        /// <paramref name="onlyDerivedTypesExclusively"/>.
        /// </summary>
        /// <param name="conventions">Not null.</param>
        /// <param name="exportType">Not null.</param>
        /// <param name="onlyDerivedTypesExclusively">Allows you to specify only
        /// <see cref="ConventionBuilder.ForTypesDerivedFrom"/> (if true), only
        /// <see cref="ConventionBuilder.ForType"/> (if false), or both (if null).
        /// If the type is abstract then ForType is not applied.</param>
        /// <returns>Returns the given <paramref name="conventions"/>
        /// for chaining.</returns>
        internal static ConventionBuilder ApplyConventions(
            this ConventionBuilder conventions,
            Type exportType,
            bool?onlyDerivedTypesExclusively)
        {
            if (conventions == null)
            {
                throw new ArgumentNullException(nameof(conventions));
            }
            if (exportType == null)
            {
                throw new ArgumentNullException(nameof(exportType));
            }
            switch (onlyDerivedTypesExclusively)
            {
            case true:
            case false when exportType.IsAbstract:
            case false when exportType.IsInterface:
                conventions.ForTypesDerivedFrom(exportType)
                .Export();
                break;

            case false:
                conventions.ForType(exportType)
                .Export();
                break;

            default:
                if (!exportType.IsInterface &&
                    !exportType.IsAbstract)
                {
                    conventions.ForType(exportType)
                    .Export();
                }
                conventions.ForTypesDerivedFrom(exportType)
                .Export();
                break;
            }
            return(conventions);
        }
Exemplo n.º 27
0
        private static ConventionBuilder GetConventions()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IFormattingFilter>()
            .Export <IFormattingFilter>();

            conventions.ForTypesDerivedFrom <ISyntaxFormattingRule>()
            .Export <ISyntaxFormattingRule>();
            conventions.ForTypesDerivedFrom <ILocalSemanticFormattingRule>()
            .Export <ILocalSemanticFormattingRule>();
            conventions.ForTypesDerivedFrom <IGlobalSemanticFormattingRule>()
            .Export <IGlobalSemanticFormattingRule>();
            // New per-analyzer options mechanism, deriving
            // from VS Workspaces functionality
            conventions.ForTypesDerivedFrom <IOptionsProvider>()
            .Export <IOptionsProvider>();

            // Legacy CodeFormatter rules options mechanism
            conventions.ForType <FormattingOptions>()
            .Export();

            conventions.ForTypesDerivedFrom <IFormattingEngine>()
            .Export <IFormattingEngine>();

            return(conventions);
        }
Exemplo n.º 28
0
        public static void Init()
        {
            try
            {
                lock (_sync)
                {
                    if (IsInitialized)
                    {
                        Dispose();
                    }

                    _logger.LogInformation("MEFLoader.Init start");
                    var startTime    = DateTime.UtcNow;
                    var rules        = new ConventionBuilder();
                    var assemblyList = new List <Assembly>();

                    if (!MEFSkip.Skip)
                    {
                        assemblies.ToList().ForEach(a =>
                        {
                            var assembly = Assembly.LoadFile(a);
                            assemblyList.Add(assembly);

                            var sharedExports = assembly.GetTypes()
                                                .Where(type => type.GetCustomAttribute <SharedPolicyCreationAttribute>(true) is SharedPolicyCreationAttribute policy && policy.Shared).ToList();
                            foreach (var item in sharedExports)
                            {
                                rules.ForTypesDerivedFrom(item).Shared();
                            }

                            var debug = assembly.GetTypes().Where(t => t.GetCustomAttribute <ExportAttribute>(true) is ExportAttribute export);
                            foreach (var t in debug)
                            {
                                _logger.LogInformation(t.FullName);
                            }
                            _logger.LogInformation($"Added types from {a} to the assembly list.");
                        });
                    }
                    _compositionHost = new ContainerConfiguration().WithAssemblies(assemblyList, rules).CreateContainer();

                    _logger.LogInformation($"MEF Init Time (in ms): {DateTime.UtcNow - startTime}");
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                ex.LoaderExceptions.ToList().ForEach(e =>
                {
                    _logger.LogError($"---: {e.Message}");
                    e.InnerException.ActIfNotNull(() => _logger.LogError(e.InnerException.ToJsonString()));
                });
            }
        }
        private static ConventionBuilder GetConventions()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom<IFormattingFilter>()
                .Export<IFormattingFilter>();

            conventions.ForTypesDerivedFrom<ISyntaxFormattingRule>()
                .Export<ISyntaxFormattingRule>();
            conventions.ForTypesDerivedFrom<ILocalSemanticFormattingRule>()
                .Export<ILocalSemanticFormattingRule>();
            conventions.ForTypesDerivedFrom<IGlobalSemanticFormattingRule>()
                .Export<IGlobalSemanticFormattingRule>();

            conventions.ForType<Options>()
                .Export();

            conventions.ForTypesDerivedFrom<IFormattingEngine>()
                .Export<IFormattingEngine>();

            return conventions;
        }
        public void ConventionBuilderExportsOpenGenerics()
        {
            var rb = new ConventionBuilder();

            rb.ForTypesDerivedFrom(typeof(IRepository <>))
            .Export(eb => eb.AsContractType(typeof(IRepository <>)));

            var c = new ContainerConfiguration()
                    .WithPart(typeof(EFRepository <>), rb)
                    .CreateContainer();

            var r = c.GetExport <IRepository <string> >();
        }
Exemplo n.º 31
0
        private static AttributedModelProvider DefineConventions()
        {
            var rb = new ConventionBuilder();

            rb.ForTypesDerivedFrom <IController>().Export();

            //rb.ForTypesDerivedFrom<IHttpController>().Export();

            //rb.ForTypesMatching(IsAPart)
            //    .Export()
            //    .ExportInterfaces();

            return(rb);
        }
Exemplo n.º 32
0
        protected IList <CryptoFactoryBase> GetFactoriesFromAssemblies()
        {
            var dir = Directory.GetCurrentDirectory() + @"\Extensions";

            if (!Directory.Exists(dir))
            {
                throw new InvalidOperationException($"Директории с крипто библиотеками не существует.")
                      {
                          Source = GetType().AssemblyQualifiedName
                      }
            }
            ;

            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <CryptoFactoryBase>().Export <CryptoFactoryBase>().Shared();

            var ass = DependencyContext.Default.GetDefaultAssemblyNames();

            string[] dllsLintInExtensions =
                Directory.GetFiles(dir, "*dll", SearchOption.TopDirectoryOnly).ToArray();
            var dllsFileInfo = dllsLintInExtensions.Select(s => new FileInfo(s)).ToArray();
            var assemblies   =
                dllsFileInfo.Select(s =>
            {
                var first = ass.FirstOrDefault(name => s.Name.Contains(name.Name));
                if (first == null)
                {
                    return(AssemblyLoadContext.Default.LoadFromAssemblyPath(s.FullName));
                }
                else
                {
                    return(AssemblyBuilder.Load(first));
                }
                //var assName = new AssemblyName(s.FullName);
                //if (first == null)
                //    return AssemblyLoadContext.Default.LoadFromAssemblyPath(s.FullName);
                //else
                //    return Assembly.Load(first);
            }).ToArray();

            var configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            using (var container = configuration.CreateContainer())
            {
                var factories = container.GetExports <CryptoFactoryBase>();
                CryptoFactories = factories.ToArray();
                return(CryptoFactories);
            }
        }
Exemplo n.º 33
0
        internal async Task <bool> LoadAsync(bool isEnabled)
        {
            if (!isEnabled)
            {
                return(false);
            }

            var assemblyCollection = LoadAssemblies();

            if (assemblyCollection == null || assemblyCollection.Count <= 0)
            {
                Logger.Trace("No assemblies found.");
                return(false);
            }

            assemblyCollection.Add(Assembly.GetExecutingAssembly());
            await ModuleLoaderSemaphore.WaitAsync().ConfigureAwait(false);

            try {
                ConventionBuilder conventions = new ConventionBuilder();
                conventions.ForTypesDerivedFrom <IModule>().Export <IModule>();
                ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(assemblyCollection, conventions);

                using CompositionHost container = configuration.CreateContainer();

                foreach (IModule module in container.GetExports <IModule>())
                {
                    Logger.Trace($"Loading module {module.ModuleIdentifier} ...");
                    module.ModuleIdentifier = GenerateModuleIdentifier(module);
                    ModuleWrapper <IModule> data = new ModuleWrapper <IModule>(module.ModuleIdentifier, module, true);
                    Logger.Trace($"Loaded module with id {module.ModuleIdentifier} !");

                    if (!IsExisitingModule(module))
                    {
                        Modules.Add(module);
                    }

                    ModulesCache.Add(data);
                }
            }
            catch (Exception e) {
                Logger.Exception(e);
                return(false);
            }
            finally {
                ModuleLoaderSemaphore.Release();
            }

            return(true);
        }
Exemplo n.º 34
0
        public static CompositionHost CreateContainer()
        {
            EnsurePluginsFolder();

            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <IExtension>().Export <IExtension>();

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var configuration = new ContainerConfiguration().WithAssemblies(assemblies, conventions);

            return(configuration.CreateContainer());
        }
Exemplo n.º 35
0
        private static void RegisterMefDependencyResolver()
        {
            /**----------------------------------------
             * -- 说明:程序根据规则自动的导出部件
             * -----------------------------------------
             * 1. 所有的继承IHttpController的类
             * 2. 命名空间中包含.Support的所有类
             * ----------------------------------------
             */
            var conventions = new ConventionBuilder();

            // Export 所有IHttpController到容器
            conventions.ForTypesDerivedFrom <IHttpController>()
            .Export();

            // Export namespace {*.Support.*}
            conventions.ForTypesMatching(t => t.Namespace != null &&
                                         (t.Namespace.EndsWith(".Support") || t.Namespace.Contains(".Support.") || t.Namespace.EndsWith("Impl") || t.Namespace.Contains(".Impl.")))
            .Export()
            .ExportInterfaces();


            var lstAssemlby = new List <Assembly>();


            var dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

            foreach (var item in dir.GetFiles("Intime.OPC.*.dll"))
            {
                lstAssemlby.Add(Assembly.LoadFrom(item.FullName));
            }


            //lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Repository.dll"));
            //lstAssemlby.Add(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\Intime.OPC.Service.dll"));
            lstAssemlby.Add(Assembly.GetExecutingAssembly());

            container = new ContainerConfiguration()
                        .WithDefaultConventions(conventions)

                        .WithAssemblies(lstAssemlby)
                        .CreateContainer();

            //var a = container.GetExport<IRmaService>();
            //Console.WriteLine(a);


            // 设置WebApi的DependencyResolver
            // GlobalConfiguration.Configuration.DependencyResolver = new MefDependencyResolver(container);
        }
        public void Bootstrap()
        {
            var conventions = new ConventionBuilder();
            conventions.ForTypesDerivedFrom<ICalculator>().Export<ICalculator>().Shared();
            conventions.ForType<Program>().ImportProperty<ICalculator>(p => p.Calculator);

            var configuration = new ContainerConfiguration()
                .WithDefaultConventions(conventions)
                .WithAssemblies(GetAssemblies("c:/addins"));

            using (CompositionHost host = configuration.CreateContainer())
            {
                host.SatisfyImports(this, conventions);
            }
        }
Exemplo n.º 37
0
        private void Bootstrap()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <ICalculator>().Export <ICalculator>().Shared();
            conventions.ForType <Program>().ImportProperty <ICalculator>(program => program.Calculator);

            var configuration = new ContainerConfiguration()
                                .WithDefaultConventions(conventions)
                                .WithAssemblies(GetAssemblies("c:/addins"));

            using (var host = configuration.CreateContainer())
            {
                host.SatisfyImports(this, conventions);
            }
        }
Exemplo n.º 38
0
        private static void Main(string[] args)
        {
            Console.WriteLine("开始......");
            string         ProjectPath = ConfigurationManager.AppSettings.Get("ProjectPath");
            Project        Pj;
            List <Conmgr>  Conmgrs;
            List <Package> Packages;
            Dictionary <int, EzOleDbConnectionManager> CMS;

            using (AutossisEntities db = new AutossisEntities())
            {
                Pj       = db.Project.Where(p => p.ProjectName == projectName).First();
                Conmgrs  = db.Conmgr.Where(p => p.ProjectId == Pj.ProjectId).ToList();
                Packages = db.Package.Where(p => p.ProjectId == Pj.ProjectId).ToList();
                CMS      = getOledbConnectionManagers(Conmgrs);
            }

            ConventionBuilder conventions = new ConventionBuilder();

            conventions
            .ForTypesDerivedFrom <ICreatePackage>()
            .Export <ICreatePackage>()
            .Shared();


            Assembly[] assemblies = new[] { typeof(Program).GetTypeInfo().Assembly };

            ContainerConfiguration configuration = new ContainerConfiguration()
                                                   .WithAssemblies(assemblies, conventions);

            ICreatePackage Cp;

            using (CompositionHost container = configuration.CreateContainer())
            {
                Cp = container.GetExport <ICreatePackage>(ConfigurationManager.AppSettings.Get("ProjectType"));
                Cp.ezOleDbConnectionManagers = CMS;
            }
            foreach (Package package in Packages)
            {
                ez.AddPackage(Cp.Create(package));
                Console.WriteLine(package.PackageName + " 生成成功。");
            }
            JobControl(Pj, null);
            ez.SaveTo(ProjectPath + Pj.ProjectName + ".ispac");
            Console.WriteLine("全部成功!");
            Console.ReadKey();
        }
Exemplo n.º 39
0
        /// <summary>
        /// Composes C# script class imports.
        /// </summary>
        /// <typeparam name="T">The script class type</typeparam>
        /// <param name="assembly">The compiled assembly.</param>
        /// <returns>The imported script objects collection.</returns>
        public static IEnumerable <T> Compose <T>(Assembly assembly)
        {
            var builder = new ConventionBuilder();

            builder.ForTypesDerivedFrom <T>()
            .Export <T>()
            .SelectConstructor(selector => selector.FirstOrDefault());

            var configuration = new ContainerConfiguration()
                                .WithAssembly(assembly)
                                .WithDefaultConventions(builder);

            using (var container = configuration.CreateContainer())
            {
                return(container.GetExports <T>());
            }
        }
Exemplo n.º 40
0
        public void Bootstrap()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <ICalculator>().Export <ICalculator>().Shared();
            conventions.ForType <Program>().ImportProperty <ICalculator>(p => p.Calculator);

            var cur           = Directory.GetCurrentDirectory();
            var configuration = new ContainerConfiguration()
                                .WithDefaultConventions(conventions)
                                .WithAssemblies(GetAssemblies(cur));

            using (CompositionHost host = configuration.CreateContainer())
            {
                host.SatisfyImports(this, conventions);
            }
        }
Exemplo n.º 41
0
        public void MapType_ShouldReturnProjectedAttributesForType()
        {
            var builder = new ConventionBuilder();

            builder.
                ForTypesDerivedFrom<IFoo>().
                Export<IFoo>();

            var fooImplAttributes = builder.GetDeclaredAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo());
            var fooImplWithConstructorsAttributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), typeof(FooImplWithConstructors).GetTypeInfo());

            var exports = new List<object>();

            exports.AddRange(fooImplAttributes);
            exports.AddRange(fooImplWithConstructorsAttributes);
            Assert.Equal(2, exports.Count);

            foreach (var exportAttribute in exports)
            {
                Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType);
                Assert.Null(((ExportAttribute)exportAttribute).ContractName);
            }
        }
Exemplo n.º 42
0
        private static void ConfigureMef()
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom<ViewModelBase>()
                       .Export();

            conventions.ForTypesMatching(x => x.Name.EndsWith("Service"))
                       .ExportInterfaces();

            ViewLocator.BuildMefConventions(conventions);

            var configuration = new ContainerConfiguration()
                .WithAssembly(typeof(App).GetTypeInfo().Assembly, conventions)
                .WithAssembly(typeof(LinquaLib).GetTypeInfo().Assembly, conventions)
                .WithAssembly(typeof(FrameworkUwp).GetTypeInfo().Assembly)
                .WithProvider(new DefaultExportDescriptorProvider());

            var container = configuration.CreateContainer();

            CompositionManager.Initialize(container);

            App.CompositionManager = CompositionManager.Current;
        }
        public static IDependencyResolver CreateWithDefaultConventions(Assembly[] appAssemblies)
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom<IHttpController>()
                .Export();

            conventions.ForTypesMatching(t => t.Namespace != null && t.Namespace.EndsWith(".Parts"))
                .Export()
                .ExportInterfaces();

            var container = new ContainerConfiguration()
                .WithAssemblies(appAssemblies, conventions)
                .CreateContainer();

            return new MefDependencyResolver(container);
        }
Exemplo n.º 44
0
        public void AddMetadata_AddsExportMetadataAttribute()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export(e => e.AddMetadata("name", "val"));

            ExportMetadataAttribute exportAtt = GetExportMetadataAttribute(builder);
            Assert.Equal("name", exportAtt.Name);
            Assert.Equal("val", exportAtt.Value);
        }
Exemplo n.º 45
0
        public void AddMetadataFuncVal_AddsExportMetadataAttribute()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export(e => e.AddMetadata("name", t => t.Name));

            ExportMetadataAttribute exportAtt = GetExportMetadataAttribute(builder);
            Assert.Equal("name", exportAtt.Name);
            Assert.Equal(typeof(FooImpl).Name, exportAtt.Value);
        }
Exemplo n.º 46
0
        public void AsContractName_AndContractType_ComputeContractNameFromType()
        {
            var builder = new ConventionBuilder();
            builder.ForTypesDerivedFrom<IFoo>().Export(e => e.AsContractName(t => "Contract:" + t.FullName).AsContractType<IFoo>());

            ExportAttribute exportAtt = GetExportAttribute(builder);
            Assert.Equal("Contract:" + typeof(FooImpl).FullName, exportAtt.ContractName);
            Assert.Equal(typeof(IFoo), exportAtt.ContractType);
        }