public void StandardExportInterfacesShouldWork()
        {
            // Export all interfaces except IDisposable, Export contracts on types without interfaces. except for disposable types
            var builder = new ConventionBuilder();
            builder.ForTypesMatching((t) => true).ExportInterfaces();
            builder.ForTypesMatching((t) => t.GetTypeInfo().ImplementedInterfaces.Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();

            var container = new ContainerConfiguration()
                .WithPart<Standard>(builder)
                .WithPart<Dippy>(builder)
                .WithPart<Derived>(builder)
                .WithPart<BareClass>(builder)
                .CreateContainer();

            var importer = new Importer();
            container.SatisfyImports(importer);

            Assert.NotNull(importer.First);
            Assert.True(importer.First.Count() == 3);
            Assert.NotNull(importer.Second);
            Assert.True(importer.Second.Count() == 3);
            Assert.NotNull(importer.Third);
            Assert.True(importer.Third.Count() == 3);
            Assert.NotNull(importer.Fourth);
            Assert.True(importer.Fourth.Count() == 3);
            Assert.NotNull(importer.Fifth);
            Assert.True(importer.Fifth.Count() == 3);

            Assert.Null(importer.Base);
            Assert.Null(importer.Derived);
            Assert.Null(importer.Dippy);
            Assert.Null(importer.Standard);
            Assert.Null(importer.Disposable);
            Assert.NotNull(importer.BareClass);
        }
        public static void CompleteInitialization()
        {
            Assembly[] partsAssemblies;

            lock (_initLock)
            {
                if (_isInitialized)
                    return;

                _isInitialized = true;

                partsAssemblies = _partAssemblies.Union(FindWebApplicationAssemblies()).ToArray();
            }

            var conventions = new ConventionBuilder()
                .WithMvcConventions()
                .WithEagerConstructionSupport();

            conventions.ForTypesUnderNamespace("Parts").Export().ExportInterfaces();

            var container = new ContainerConfiguration()
                .WithDefaultConventions(conventions)
                .WithAssemblies(partsAssemblies)
                .WithApplicationSettings()
                .CreateContainer();

            MvcCompositionProvider.Initialize(container);
            CompositionFilterProvider.Install(FilterProviders.Providers);
            ImportCapableFilterAttributeFilterProvider.Install(FilterProviders.Providers);

            container.ConstructEagerParts();
        }
		public void Basic()
		{
			var types = new[] { typeof(Singleton) }.AsApplicationParts();
			var container = new ContainerConfiguration().WithParts( types.AsEnumerable() ).WithProvider( SingletonExportDescriptorProvider.Default ).CreateContainer();
			var export = container.GetExport<Singleton>();
			Assert.Same( Singleton.Default, export );
		}
Example #4
0
        /// <summary>
        /// 遅延初期化処理。
        /// </summary>
        /// <param name="token"></param>
        private void Init(CancellationToken token, TaskScheduler uiSyncContext, Assembly callerAssembly)
        {
            logger.Trace("Init Start");
            try
            {
                // MEFの構成
                var qAssm = new[] { 
                    this.GetType().Assembly,
                    Assembly.GetEntryAssembly(),
                    callerAssembly, 
                    typeof(Pasta.Logging.PastaLogger).Assembly,
                    typeof(Pasta.Gleaners.Net.MailGleaner).Assembly,
                }
                    .Where(a => a != null)
                    .Distinct();
                var configuration = new ContainerConfiguration()
                    .WithAssemblies(qAssm)
                    ;
                var host = configuration.CreateContainer();
                token.Register(() => host.Dispose());

                // appの取得と構成
                var app = host.GetExport<AppCore>();
                app.Init(token,uiSyncContext);
                Application = app;
                logger.Trace("Init End");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
		public void Implementation()
		{
			var types = new[] { typeof(Implemented) }.AsApplicationParts();
			var container = new ContainerConfiguration().WithParts( types.AsEnumerable() ).WithProvider( SingletonExportDescriptorProvider.Default ).CreateContainer();
			Assert.Same( Implemented.Default, container.GetExport<ISingleton>() );
			Assert.Same( Implemented.Default, container.GetExport<Implemented>() );
		}
Example #6
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();
        }
Example #7
0
        private CompositionContext CreateContainer(params Type[] types)
        {
            var configuration = new ContainerConfiguration()
                .WithParts(types)
                .WithProvider(new DictionaryExportDescriptorProvider());

            return configuration.CreateContainer();
        }
 public void InitializeContainer(params Type[] parts)
 {
     var configuration = new ContainerConfiguration().WithParts(parts);
     using (CompositionHost host = configuration.CreateContainer())
     {
         host.SatisfyImports(_calcImport);
     }
 }
		public void Many()
		{
			var types = new[] { typeof(Implemented), typeof(AnotherImplemented) }.AsApplicationParts();
			var container = new ContainerConfiguration().WithParts( types.AsEnumerable() ).WithProvider( SingletonExportDescriptorProvider.Default ).CreateContainer();
			var exports = container.GetExports<ISingleton>().Fixed();
			Assert.Contains( Implemented.Default, exports );
			Assert.Contains( AnotherImplemented.Default, exports );
		}
 public void QueryProviders(IEnumerable<Assembly> assemblies)
 {
     var configuration = new ContainerConfiguration().WithAssemblies(assemblies);
     using (var container = configuration.CreateContainer())
     {
         container.SatisfyImports(this);
     }
 }
        private static IServiceLocator BuildLocator()
        {
            var configuration = new ContainerConfiguration();
            configuration.RegisterComponents(typeof(IFoo).Assembly);

            var container = configuration.CreateContainer();

            return new MefServiceLocator(container);
        }
Example #12
0
 private CompositionHost GetContainer(IEnumerable<Assembly> assemblies)
 {
     var configuration = new ContainerConfiguration();
     foreach (var assembly in assemblies)
     {
         configuration.WithAssembly(assembly);
     }
     return configuration.CreateContainer();
 }
        public void ProvidersCanDetectAbsenceOfAContractItSupports()
        {
            var container = new ContainerConfiguration()
                .WithProvider(new DefaultObjectExportDescriptorProvider())
                .CreateContainer();

            var o = container.GetExport<object>();
            Assert.Equal(DefaultObjectExportDescriptorProvider.DefaultObject, o);
        }
Example #14
0
        public MainPage()
        {
            var containerConfiguration = new ContainerConfiguration().WithAssembly(typeof(App).GetTypeInfo().Assembly);
            CompositionHost host = containerConfiguration.CreateContainer();
            host.SatisfyImports(this);

            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }
        public void ProvidersCanLocateImplementationsOfAContractItSupports()
        {
            var container = new ContainerConfiguration()
                .WithProvider(new DefaultObjectExportDescriptorProvider())
                .WithPart<ExportsObject>()
                .CreateContainer();

            var o = container.GetExport<object>();
            Assert.NotEqual(DefaultObjectExportDescriptorProvider.DefaultObject, o);
        }
Example #16
0
        protected void Compose()
        {
            // Create the container
            var config = new ContainerConfiguration();
            ConfigureContainer(config);
            _container = config.CreateContainer();

            // Compose the application
            _container.SatisfyImports(this);
        }
 public void Bootstrapper()
 {
     var configuration = new ContainerConfiguration()
         .WithPart<Calculator>();
     using (CompositionHost host = configuration.CreateContainer())
     {
         // Calculator = host.GetExport<ICalculator>();
         host.SatisfyImports(this);
     }
 }
Example #18
0
        /// <summary>
        /// Singleton instance of the MEF catalog
        /// </summary>
        //public static CompositionContainer Container { get; set; }

        /// <summary>
        /// Static constructor responsible to create the MEF container
        /// </summary>
        static EV5MefContainer()
        {
            var configuration = new ContainerConfiguration()
    .WithAssembliesInPath(path, conventions);
           

            //var catalog = CatalogProvider.CurrentProvider.CreateCatalog();

            //Container = new CompositionContainer(catalog);
        }
        public void MetadataViewsCanCarryDefaultValues()
        {
            var cc = new ContainerConfiguration()
                        .WithPart<HasNoName>()
                        .CreateContainer();

            var hn = cc.GetExport<Lazy<HasNoName, OptionallyNamed>>();

            Assert.Equal("B", hn.Metadata.Name);
        }
        public void AConcreteTypeWithDictionaryConstructorIsAMetadataView()
        {
            var cc = new ContainerConfiguration()
                        .WithPart<HasNameA>()
                        .CreateContainer();

            var hn = cc.GetExport<Lazy<HasNameA, DictionaryName>>();

            Assert.Equal("A", hn.Metadata.RetrievedName);
        }
		public void Enumerable()
		{
			var parts = typeof(ExportedClass).Append( typeof(AnotherExportedClass) ).AsApplicationParts();
			var container = new ContainerConfiguration().WithParts( parts.AsEnumerable() ).CreateContainer();
			var exports = new ServiceLocator( container ).Get<IEnumerable<IExported>>( typeof(IEnumerable<IExported>) );
			var exported = exports.WhereAssigned().Fixed();
			Assert.Equal( 2, exported.Length );
			Assert.Single( exported.OfType<AnotherExportedClass>() );
			Assert.Single( exported.OfType<ExportedClass>() );
		}
        public void AConcreteTypeWithWritablePropertiesIsAMetadataView()
        {
            var cc = new ContainerConfiguration()
                        .WithPart<HasNameA>()
                        .CreateContainer();

            var hn = cc.GetExport<Lazy<HasNameA, Named>>();

            Assert.Equal("A", hn.Metadata.Name);
        }
        public void AConcreteTypeWithUnsupportedConstructorsCannotBeUsedAsAMetadataView()
        {
            var cc = new ContainerConfiguration()
                        .WithPart<HasNameA>()
                        .CreateContainer();

            var x = Assert.Throws<CompositionFailedException>(() => cc.GetExport<Lazy<HasNoName, InvalidConcreteView>>());

            Assert.Equal("The type 'InvalidConcreteView' cannot be used as a metadata view. A metadata view must be a concrete class with a parameterless or dictionary constructor.", x.Message);
        }
Example #24
0
        protected override void OnInitialize()
        {
            base.OnInitialize();

            Context = UnitTestSynchronizationContext.Create();

            var configuration = new ContainerConfiguration()
                .WithAssembly(typeof(ShellViewModel).GetTypeInfo().Assembly)
                .WithAssembly(typeof(ApplicationsTest).GetTypeInfo().Assembly);
            Container = configuration.CreateContainer();
        }
        public void SampleServicesCorrectlyImported()
        {
            var container = new ContainerConfiguration()
                .WithPart<SampleService1>()
                .CreateContainer();

            var importer = new LooseImporter();
            container.SatisfyImports(importer);

            Assert.Equal(1, importer.Services.Count);
        }
        protected void Application_Start()
        {
            SetupAutoMapper();
            var container = new ContainerConfiguration()
                                    .WithAssembly(typeof(WebApiApplication).Assembly)
                                    .CreateContainer();

            var resolver = new StandaloneDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
            GlobalConfiguration.Configure(container.GetExport<WebApiConfig>().Register);
        }
 private static void RegisterComplexObject(ContainerConfiguration config)
 {
     config.WithParts(
         typeof (FirstService),
         typeof (SecondService),
         typeof (ThirdService),
         typeof (SubObjectOne),
         typeof (SubObjectTwo),
         typeof (SubObjectThree),
         typeof (Complex));
 }
Example #28
0
		private static void Main(string[] args) {
			var configuration = new ContainerConfiguration()
				.WithAssembly(typeof(Channel).Assembly)
				.WithPart(typeof(DesktopCryptoProvider))
				.WithPart(typeof(DesktopChannel))
				.WithPart(typeof(Program));
			var container = configuration.CreateContainer();
			
			var program = container.GetExport<Program>();
			program.DoAsync().GetAwaiter().GetResult();
		}
        public override Action GetOperation()
        {
            var c = new ContainerConfiguration()
                .WithPart(typeof(X))
                .CreateContainer();

            return () =>
            {
                c.GetExport<X>();
            };
        }
		public override ContainerConfiguration Get( ContainerConfiguration parameter )
		{
			var mappings = source();
			var builder = new ConventionBuilder();
			foreach ( var mapping in mappings )
			{
				builder.ForType( mapping.Subject ).Export( conventionBuilder => conventionBuilder.AsContractType( mapping.ExportAs ?? mapping.Subject ) );	
			}
			var subjects = mappings.Select( mapping => mapping.Subject );
			var result = parameter.WithParts( subjects, builder );
			return result;
		}
Example #31
0
        public void ConventionsCanApplyImportsToInheritedProperties()
        {
            var conventions = new ConventionBuilder();

            conventions.ForType <Imported>().Export();
            conventions.ForType <DerivedFromBaseWithImport>()
            .ImportProperty(b => b.Imported)
            .Export();

            var container = new ContainerConfiguration()
                            .WithDefaultConventions(conventions)
                            .WithParts(typeof(Imported), typeof(DerivedFromBaseWithImport))
                            .CreateContainer();

            var dfb = container.GetExport <DerivedFromBaseWithImport>();

            Assert.IsAssignableFrom(typeof(Imported), dfb.Imported);
        }
Example #32
0
        public static void Initialize(TestContext tc)
        {
            InitialConfiguration.Set(Constants.ConfigSettingName_ServiceKeyVaultName, "someservicekeyvault");
            InitialConfiguration.Set(Constants.ConfigSettingName_RuntimeKeyVaultName, "somekeyvault");
            InitialConfiguration.Set(Constants.ConfigSettingName_MetricEventHubConnectionKey, "metric-eventhubconnectionstring");
            InitialConfiguration.Set(Constants.ConfigSettingName_EnableOneBox, "true");
            InitialConfiguration.Set(Constants.ConfigSettingName_ClusterName, "localCluster");
            InitialConfiguration.Set(Constants.ConfigSettingName_ConfigFolderContainerPath, "");
            InitialConfiguration.Set(Constants.ConfigSettingName_ConfigFolderHost, new System.Uri(Environment.CurrentDirectory).AbsoluteUri);
            InitialConfiguration.Set(Constants.ConfigSettingName_LocalMetricsHttpEndpoint, "http://localhost:2020/api/data/upload");

            var conf = new ContainerConfiguration()
                       .WithAssembly(typeof(ConfigGenConfiguration).Assembly)
                       .WithAssembly(typeof(DataX.Config.Local.LocalDesignTimeStorage).Assembly);

            CompositionHost = conf.CreateContainer();
            _TestContext    = tc;
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            // Self-register and set up service location
            var container = ContainerConfiguration.Create();

            // Auto register all the global configuration tasks
            //container.ConfigureAutoRegistration()
            //     .Include(x => x.Implements<IGlobalConfigurationTask>(),
            //              Then.Register().As<IGlobalConfigurationTask>().WithTypeName())
            //     .ApplyAutoRegistration(new[] { GetType().Assembly, typeof(BrokerCommodityConfiguration).Assembly });

            // Register all IGlobalConfigurationTasks from this and any other appropriate assemblies
            // NB This needs fixing so we don't have to name them - needs specific IDependencyResolver
            // see http://www.chrisvandesteeg.nl/2009/04/16/making-unity-work-more-like-the-others/
            container.RegisterType <IGlobalConfigurationTask, SampleMappingContextConfiguration>("a");
            container.RegisterType <IGlobalConfigurationTask, RouteConfiguration>("b");
            container.RegisterType <IGlobalConfigurationTask, ServiceConfiguration>("c");
            container.RegisterType <IGlobalConfigurationTask, SimpleMappingEngineConfiguration>("d");
            container.RegisterType <IGlobalConfigurationTask, RepositoryConfiguration>("e");
            // container.RegisterType<IGlobalConfigurationTask, ProfilingConfiguration>("e");
            container.RegisterType <IGlobalConfigurationTask, LoggerConfiguration>("f");

            // Per-entity configurations
            container.RegisterType <IGlobalConfigurationTask, BrokerConfiguration>("broker");
            container.RegisterType <IGlobalConfigurationTask, CounterpartyConfiguration>("counterparty");
            container.RegisterType <IGlobalConfigurationTask, ExchangeConfiguration>("exchange");
            container.RegisterType <IGlobalConfigurationTask, LocationConfiguration>("location");
            container.RegisterType <IGlobalConfigurationTask, PartyConfiguration>("party");
            container.RegisterType <IGlobalConfigurationTask, PartyRoleConfiguration>("partyrole");
            container.RegisterType <IGlobalConfigurationTask, PersonConfiguration>("person");
            container.RegisterType <IGlobalConfigurationTask, SourceSystemConfiguration>("sourcesystem");
            container.RegisterType <IGlobalConfigurationTask, LegalEntityConfiguration>("legalentity");

            // Some dependencies for the tasks
            container.RegisterInstance(RouteTable.Routes);

            // Now get them all, and initialize them, bootstrapper takes care of ordering
            var globalTasks = container.ResolveAll <IGlobalConfigurationTask>();
            var tasks       = globalTasks.Select(task => task as IConfigurationTask).ToList();

            ConfigurationBootStrapper.Initialize(tasks);

            ServiceLocator = container.Resolve <IServiceLocator>();
        }
        public CompositionHost Build()
        {
            var options        = _serviceProvider.GetRequiredService <IOptionsMonitor <OmniSharpOptions> >();
            var memoryCache    = _serviceProvider.GetRequiredService <IMemoryCache>();
            var loggerFactory  = _serviceProvider.GetRequiredService <ILoggerFactory>();
            var assemblyLoader = _serviceProvider.GetRequiredService <IAssemblyLoader>();
            var config         = new ContainerConfiguration();

            var fileSystemWatcher = new ManualFileSystemWatcher();
            var metadataHelper    = new MetadataHelper(assemblyLoader);

            var logger = loggerFactory.CreateLogger <CompositionHostBuilder>();

            // We must register an MSBuild instance before composing MEF to ensure that
            // our AssemblyResolve event is hooked up first.
            var msbuildLocator = _serviceProvider.GetRequiredService <IMSBuildLocator>();

            RegisterMSBuildInstance(msbuildLocator, logger);

            config = config
                     .WithProvider(MefValueProvider.From(_serviceProvider))
                     .WithProvider(MefValueProvider.From <IFileSystemNotifier>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From <IFileSystemWatcher>(fileSystemWatcher))
                     .WithProvider(MefValueProvider.From(memoryCache))
                     .WithProvider(MefValueProvider.From(loggerFactory))
                     .WithProvider(MefValueProvider.From(_environment))
                     .WithProvider(MefValueProvider.From(_writer))
                     .WithProvider(MefValueProvider.From(options.CurrentValue))
                     .WithProvider(MefValueProvider.From(options.CurrentValue.FormattingOptions))
                     .WithProvider(MefValueProvider.From(assemblyLoader))
                     .WithProvider(MefValueProvider.From(metadataHelper))
                     .WithProvider(MefValueProvider.From(msbuildLocator))
                     .WithProvider(MefValueProvider.From(_eventEmitter ?? NullEventEmitter.Instance));

            var parts = _assemblies
                        .Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
                        .Distinct()
                        .SelectMany(a => SafeGetTypes(a))
                        .ToArray();

            config = config.WithParts(parts);

            return(config.CreateContainer());
        }
Example #35
0
        private CompositionHost GetContainer(IEnumerable <Assembly> assemblies)
        {
            var configuration = new ContainerConfiguration();

            foreach (var assembly in assemblies)
            {
                configuration.WithAssembly(assembly);
            }
            try
            {
                return(configuration.CreateContainer());
            }
            catch (ReflectionTypeLoadException ex)
            {
                Logger.LogError(
                    $"Error when get composition container: {ex.Message}, loader exceptions: {(ex.LoaderExceptions != null ? string.Join(", ", ex.LoaderExceptions.Select(e => e.Message)) : "none")}");
                throw;
            }
        }
Example #36
0
        private IVersioning InitializeVersioning(ContainerConfiguration containerConfiguration)
        {
            IVersioning versioning;

            if (_customVersioning != null)
            {
                versioning = _customVersioning;
            }
            else
            {
                var v = new Versioning(Configuration, _options.VersioningTable);
                if (_customBootstrapper != null && !v.VersioningTableExists)
                {
                    ApplyCustomBootstrapping(v, containerConfiguration);
                }
                versioning = v;
            }
            return(versioning);
        }
Example #37
0
        private object LoadPlugin(string dllFileName, Type interfaceType)
        {
            try
            {
                var assembly      = Assembly.LoadFrom(Path.Combine(GetPluginFolderPath(), dllFileName));
                var configuration = new ContainerConfiguration().WithAssembly(assembly);

                using (var container = configuration.CreateContainer())
                {
                    object plugin = container.GetExport(interfaceType);
                    return(plugin);
                }
            }
            catch (Exception exp)
            {
                PluginLog(exp.ToString());
            }
            return(null);
        }
Example #38
0
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
        internal MainWindow()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            Loaded += OnLoaded;

            var container = new ContainerConfiguration()
                            .WithAssembly(typeof(MainViewModelBase).Assembly) // RoslynPad.Common.UI
                            .WithAssembly(typeof(MainWindow).Assembly);       // RoslynPad
            var locator = container.CreateContainer().GetExport <IServiceProvider>();

            _viewModel = locator.GetService <MainViewModelBase>();

            DataContext = _viewModel;
            InitializeComponent();
            DocumentsPane.ToggleAutoHide();

            LoadWindowLayout();
            LoadDockLayout();
        }
Example #39
0
        /// <summary>
        /// Determines that the member is injectable in the current context.
        /// </summary>
        /// <param name="configuration">The container configuration to determine that the container allows the auto injection or not.</param>
        /// <param name="contextData">The registration context to determine that the registration allows the auto injection or not.</param>
        /// <returns>True if the member is injectable, otherwise false.</returns>
        public bool CanInject(ContainerConfiguration configuration, RegistrationContextData contextData)
        {
            var autoMemberInjectionEnabled = configuration.MemberInjectionWithoutAnnotationEnabled || contextData.AutoMemberInjectionEnabled;
            var autoMemberInjectionRule    = contextData.AutoMemberInjectionEnabled ? contextData.AutoMemberInjectionRule :
                                             configuration.MemberInjectionWithoutAnnotationRule;

            if (autoMemberInjectionEnabled)
            {
                return(this.TypeInformation.ForcedDependency ||
                       this.TypeInformation.MemberType == MemberType.Field &&
                       (autoMemberInjectionRule & Rules.AutoMemberInjectionRules.PrivateFields) == Rules.AutoMemberInjectionRules.PrivateFields ||
                       this.TypeInformation.MemberType == MemberType.Property &&
                       ((autoMemberInjectionRule & Rules.AutoMemberInjectionRules.PropertiesWithPublicSetter) == Rules.AutoMemberInjectionRules.PropertiesWithPublicSetter &&
                        ((PropertyInfo)this.MemberInfo).HasSetMethod() ||
                        (autoMemberInjectionRule & Rules.AutoMemberInjectionRules.PropertiesWithLimitedAccess) == Rules.AutoMemberInjectionRules.PropertiesWithLimitedAccess));
            }

            return(this.TypeInformation.ForcedDependency);
        }
Example #40
0
        private void LoadLicensingManager()
        {
            try
            {
                var conventions = new ConventionBuilder();
                var assembly    = Assembly.LoadFrom(Path.Combine(GetPluginFolderPath(), "Licensing.dll"));

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

                using (var container = configuration.CreateContainer())
                {
                    LicensingManager = container.GetExport <ILicensingManager>();
                }
            }
            catch (Exception exp)
            {
                PluginLog(exp.ToString());
            }
        }
Example #41
0
        public void ExportMetadata()
        {
            ContainerConfiguration   cfg = new ContainerConfiguration().WithAssembly(Assembly.GetExecutingAssembly());
            ReflectionAndComposition r   = new ReflectionAndComposition();

            using (CompositionHost container = cfg.CreateContainer())
            {
                container.SatisfyImports(r);
            }
            TestOne t = r.ComposObject.Value;

            t.Run();
            IDictionary <string, object> metas = r.ComposObject.Metadata;

            foreach (var kv in metas)
            {
                Console.WriteLine($"Key:{kv.Key}, value: {kv.Value}");
            }
        }
Example #42
0
        private void LoadAssemblies(PluginSearchMode searchMode, [CanBeNull, ItemNotNull] string[] filters, [NotNull, ItemNotNull] params string[] searchPaths)
        {
            if (_extensionContainer != null)
            {
                _extensionContainer.Dispose();
                _extensionContainer = null;
            }

            var allAssemblies = FindAssemblies(searchMode, filters, searchPaths);
            var configuration = new ContainerConfiguration().WithAssemblies(allAssemblies);
            var host          = configuration.CreateContainer();

            var loadedPlugins = host.GetExports <IMilliSimPlugin>().ToArray();

            _allPlugins = loadedPlugins;

            _extensionConfiguration = configuration;
            _extensionContainer     = host;
        }
        public static List <PluginType> Load(string[] paths)
        {
            var exports = new List <PluginType>();

            paths.ToList().ForEach(path =>
            {
                var lc = new LoadContext(path);

                var assemblies = Directory.GetFiles(path, "*.dll")
                                 .Select(lc.Load).ToList();

                var configuration = new ContainerConfiguration().WithAssemblies(assemblies);
                var container     = configuration.CreateContainer();

                exports.AddRange(container.GetExports <PluginType>());
            });

            return(exports);
        }
        public static CompositionHost CreateContainer(ExtensionManager extensionManager)
        {
            var conventions = new ConventionBuilder();

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

            // TODO AppDomain here is a custom appdomain from namespace AvalonStudio.Extensibility.Utils. It is able
            // to load any assembly in the bin directory (so not really appdomain) we need to get rid of this
            // once all our default extensions are published with a manifest and copied to extensions dir.
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Distinct();

            var extensionAssemblies = LoadMefComponents(extensionManager);

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

            return(configuration.CreateContainer());
        }
Example #45
0
        static void Main(string[] args)
        {
            // WithExport() demonstrates how a pre-existing instance is used as an export.

            // WithFactoryDelegate() demonstrates how an export can be dynamically
            // provided by calling a method.

            var config = new ContainerConfiguration()
                         .WithExport <TextWriter>(Console.Out)
                         .WithFactoryDelegate <string>(() => DateTime.Now.ToString(), isShared: true)
                         .WithPart <Program>();

            using (var container = config.CreateContainer())
            {
                var p = container.GetExport <Program>();
                p.Run();
                Console.ReadKey();
            }
        }
Example #46
0
        static void Main(string[] args)
        {
            var conventions = new ConventionBuilder();

            conventions.ForTypesMatching(t => t.Namespace == typeof(Application).Namespace)
            .Export();

            var configuration = new ContainerConfiguration()
                                .WithDefaultConventions(conventions)
                                .WithAssembly(typeof(Program).Assembly);

            using (var container = configuration.CreateContainer())
            {
                var application = container.GetExport <Application>();
                application.Run("SuperIDE");
            }

            Console.ReadKey();
        }
Example #47
0
        public void Load()
        {
            var conventions = new ConventionBuilder();
            //conventions.ForType<CalculatorUser>()
            //.ImportProperty<ICalculator>(p => p.Calculator)
            //.Export();
            //conventions.ForType<ICalculator>()
            //.Export<ICalculator>()
            //.Shared();

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

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

            var assembly       = typeof(Loader).GetTypeInfo().Assembly;
            var configuration2 = new ContainerConfiguration().WithAssembly(assembly);

            container = configuration2.CreateContainer();
        }
Example #48
0
        public UserService()
        {
            //AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"D:\CovidStandard\Covid.UserService\App.Release.config");

            var queueConfig = ConfigurationManager.GetSection("queueConfiguration") as QueueConfiguration;

            string json = JsonConvert.SerializeObject(new { queueConfiguration = queueConfig });

            var serviceConfig = ConfigurationManager.GetSection("restClients") as ServiceConfiguration;

            string serviceConfigJson = JsonConvert.SerializeObject(new { services = serviceConfig.Services }, new JsonSerializerSettings()
            {
                Formatting = Newtonsoft.Json.Formatting.Indented, NullValueHandling = NullValueHandling.Ignore
            });

            ServiceConfiguration serv = new ServiceConfiguration();

            _container = ContainerConfiguration.Configure(Configuration, _eventListenerCancellationTokenSource, _cancellationTokenSource);
        }
Example #49
0
        public static RoslynWorkspace GetWorkspace(AvalonStudio.Projects.ISolution solution)
        {
            if (!s_solutionWorkspaces.ContainsKey(solution))
            {
                //await PackageManager.EnsurePackage("AvalonStudio.Languages.CSharp", IoC.Get<IConsole>());

                //var dotnetDirectory = Path.Combine(PackageManager.GetPackageDirectory("AvalonStudio.Languages.CSharp"), "content");

                var currentDir = AvalonStudio.Platforms.Platform.ExecutionPath;

                var loadedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();

                var assemblies = new[]
                {
                    // Microsoft.CodeAnalysis.Workspaces
                    typeof(WorkspacesResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.CSharp.Workspaces
                    typeof(CSharpWorkspaceResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.Features
                    typeof(FeaturesResources).GetTypeInfo().Assembly,
                    // Microsoft.CodeAnalysis.CSharp.Features
                    typeof(CSharpFeaturesResources).GetTypeInfo().Assembly,
                    typeof(RoslynWorkspace).Assembly,
                };

                var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
                                .Distinct()
                                .SelectMany(x => x.GetTypes())
                                .ToArray();

                var compositionContext = new ContainerConfiguration()
                                         .WithParts(partTypes)
                                         .CreateContainer();

                var host = MefHostServices.Create(compositionContext);

                var workspace = new RoslynWorkspace(host, null, compositionContext, DotNetCliService.Instance.Info.Executable, DotNetCliService.Instance.Info.BasePath);

                workspace.RegisterWorkspace(solution);
            }

            return(s_solutionWorkspaces[solution]);
        }
Example #50
0
        public OutputGeneratorRepository()
        {
            var executableLocation = Assembly.GetEntryAssembly().Location;
            var path = Path.Combine(Path.GetDirectoryName(executableLocation), "plugins");

            if (!Directory.Exists(path))
            {
                externalGenerators = new IOutputGenerator[0];
                return;
            }

            var assemblies = Directory
                             .GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly)
                             .Where(x =>
            {
                var fileName = Path.GetFileName(x);
                return(!fileName.StartsWith("System.") && !fileName.StartsWith("Microsoft."));
            })
                             .Select(assembly =>
            {
                try
                {
                    var asm = Assembly.LoadFrom(assembly);
                    Log.LogDebug($"Loaded {assembly}");
                    return(asm);
                }
                catch (FileLoadException ex)
                {
                    Log.LogDebug($"Failed to load {assembly}: {ex}");
                    return(null);
                }
            })
                             .Where(x => x != null)
                             .ToList();

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

            using (var container = configuration.CreateContainer())
            {
                externalGenerators = container.GetExports <IOutputGenerator>().ToList();
            }
        }
Example #51
0
        private static void Main()
        {
            var currentAssembly = typeof(Program).Assembly;
            var containerConfig = ContainerConfiguration.CreateFromAssembly(
                currentAssembly,
                initializeAutoMapper: true,
                logInitialization: true);

            InitializationService.AssureServicesAreInitialized(containerConfig, DependenciesProvider.ProvideDependencencies);
            InitializationService.AssureSettingsAreInitialized <AppSettings>(
                AppSettings.Sectionkey,
                string.Empty,
                currentAssembly);

            ServiceLocatorSingleton
            .Instance
            .GetService <IConsoleCommandsStartupService>()
            .Start();
        }
        private static ContainerConfiguration LoadPluginAssemblies()
        {
            var directory = AppDomain.CurrentDomain.BaseDirectory;

            AssemblyFinder.Current = new AssemblyFinder(directory);

            var assemblies = AssemblyFinder.Current.GetAssemblies("CBTS-PLUGIN");

            if (!assemblies.Any())
            {
                throw new Exception("No plugins found, exiting");
            }

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

            return(configuration);
        }
        public static ContainerConfiguration WithPartsFromXml(
            this ContainerConfiguration configuration,
            string configurationSectionName = Constants.DefaultConfigurationSectionName)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            if (configurationSectionName == null)
            {
                throw new ArgumentNullException("configurationSectionName");
            }

            var section = (ConfigurationSection)ConfigurationManager.GetSection(configurationSectionName);

            var types = new List <Type>();
            var registrationBulider = new ConventionBuilder();

            foreach (var partConfiguration in section.Parts)
            {
                var type = Type.GetType(partConfiguration.Type);
                types.Add(type);

                var partBuilder = registrationBulider.ForType(type);
                var exported    = false;

                foreach (var export in partConfiguration.Exports)
                {
                    exported = true;
                    var contractType = Type.GetType(export.ContractType);
                    partBuilder.Export(eb => eb.AsContractType(contractType));
                }

                if (!exported)
                {
                    partBuilder.Export();
                }
            }

            configuration.WithParts(types, registrationBulider);

            return(configuration);
        }
        public void WithProvider_ValidProvider_RegistersProvider()
        {
            var configuration = new ContainerConfiguration();

            var provider = new ExportProvider {
                Result = 10
            };

            Assert.Same(configuration, configuration.WithProvider(provider));

            CompositionHost container = configuration.CreateContainer();

            Assert.Equal(0, provider.CalledGetExportDescriptors);
            Assert.Equal(0, provider.CalledGetExportDescriptors);

            Assert.Equal(10, container.GetExport <int>());
            Assert.Equal(1, provider.CalledGetExportDescriptors);
            Assert.Equal(1, provider.CalledGetExportDescriptors);
        }
Example #55
0
        private void LoadSensorHandlers()
        {
            var assemblies = Directory
                             .GetFiles("./", "MEF.*.dll", SearchOption.AllDirectories)
                             .Select(x => Path.Combine(Directory.GetCurrentDirectory(), x))
                             .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath)
                             .ToList();

            var conventions = new ConventionBuilder();

            conventions.ForTypesDerivedFrom <ISensorHandlerContract>()
            .Export <ISensorHandlerContract>()
            .Shared();
            var configuration = new ContainerConfiguration()
                                .WithAssemblies(assemblies, conventions);

            _sensorhandlerContainer = configuration.CreateContainer();
            _sensorhandlers         = _sensorhandlerContainer.GetExports <ISensorHandlerContract>();
        }
        public PluginSet LoadPlugins()
        {
            try
            {
                var executableLocation = Assembly.GetEntryAssembly().Location;
                _logger.LogDebug($"executable location: {executableLocation}");

                var pluginRootDirectory = Path.GetDirectoryName(executableLocation) ?? throw new InvalidOperationException();
                _logger.LogDebug($"plugin root directory: {executableLocation}");

                var assemblies = Directory
                                 .GetFiles(pluginRootDirectory, "*.dll", SearchOption.AllDirectories)
                                 .Where(f => f.Contains("Emb.TargetProvider") || f.Contains("Emb.DataSourceProvider"))
                                 .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath)
                                 .ToList();
                _logger.LogDebug("found assemblies: " + string.Join(", ", assemblies.Select(assembly => assembly.FullName)));

                var configuration = new ContainerConfiguration()
                                    .WithAssemblies(assemblies);
                using (var container = configuration.CreateContainer())
                {
                    DataSourceProviders = container.GetExports <IDataSourceProvider>();
                    TargetProviders     = container.GetExports <ITargetProvider>();
                }

                var result = new PluginSet()
                {
                    DataSourceProviders = DataSourceProviders.ToList(),
                    TargetProviders     = TargetProviders.ToList(),
                };

                _logger.LogDebug("found data source providers: " + string.Join(", ", result.DataSourceProviders.Select(dataSourceProvider => dataSourceProvider.GetType().Name)));
                _logger.LogDebug("found targets: " + string.Join(", ", result.TargetProviders.Select(dataSourceProvider => dataSourceProvider.GetType().Name)));

                return(result);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "can't load plugins");
                return(new PluginSet());
            }
        }
Example #57
0
        private static async Task LoadImplementInterfaceAsync()
        {
            var assembly      = Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features");
            var configuration = new ContainerConfiguration().WithAssembly(assembly);
            var container     = configuration.CreateContainer();
            var test          = container.GetExports <CodeFixProvider>().ToArray();
            var test2         = test.FirstOrDefault(provider =>
                                                    (Attribute.GetCustomAttribute(provider.GetType(), typeof(ExportCodeFixProviderAttribute)) as ExportCodeFixProviderAttribute)?.Name == "ImplementInterface");
            string solutionFile = Path.Combine(
                Path.GetDirectoryName(typeof(Program).Assembly.Location),
                @"..\..\..\..\CSharpDom.sln");

            solutionFile = Path.GetFullPath(solutionFile);
            SolutionWithCodeAnalysis solution = await SolutionWithCodeAnalysis.OpenAsync(solutionFile);

            //(Workspace, ProjectWithCodeAnalysis) project = await ProjectWithCodeAnalysis.OpenWithWorkspaceAsync(projectFile);
            DocumentWithCodeAnalysis document = solution.Projects
                                                .First(project => project.Syntax.Name == "CSharpDom.EditableInterfaceGenerator")
                                                .Documents.First();
            Compilation compilation = await document.Syntax.Project.GetCompilationAsync();

            //SyntaxGenerator generator = document.Syntax.get
            LoadedDocumentWithCodeAnalysis loadedDocument = await document.LoadAsync();

            var syntax = loadedDocument.Namespaces.First().Classes.SealedClasses.First().ImplementedInterfaces.First().Syntax;
            List <CodeAction> actions = new List <CodeAction>();
            var            descriptor = new DiagnosticDescriptor("CS0535", "CS0535", "CS0535", "CS0535", DiagnosticSeverity.Error, true);
            CodeFixContext context    = new CodeFixContext(
                document.Syntax,
                Diagnostic.Create(descriptor, Location.Create(syntax.SyntaxTree, syntax.Span)),
                (action, diagnostics) => actions.Add(action),
                CancellationToken.None);
            await test2.RegisterCodeFixesAsync(context);

            var operations = await actions[0].GetOperationsAsync(CancellationToken.None);

            foreach (var operation in operations)
            {
                operation.Apply(solution.Syntax.Workspace, CancellationToken.None);
            }
            actions.GetHashCode();
        }
Example #58
0
        private static async Task CreatePoolIfNotExist(BatchClient batchClient, string poolId, ResourceFile[] resourceFiles)
        {
            var pools = await batchClient.PoolOperations.ListPools().ToListAsync();

            var alreadyExists = pools.Any(x => x.Id == poolId);

            if (alreadyExists)
            {
                Console.WriteLine($"Pool {poolId} already exists, no need to create");
                return;
            }

            Console.WriteLine($"Creating pool {poolId}");

            var containerRegistry = new ContainerRegistry("globomantics", "globomantics.azurecr.io",
                                                          "jWyBhM8qiNG3zX/S8GGDbJe5r5aMvpW7");

            var containerConfig = new ContainerConfiguration()
            {
                ContainerImageNames = new List <string>
                {
                    @"globomantics.azurecr.io/optionpricer:latest"
                },
                ContainerRegistries = new List <ContainerRegistry>
                {
                    containerRegistry
                }
            };

            var pool = batchClient.PoolOperations.CreatePool(
                poolId: poolId,
                targetLowPriorityComputeNodes: 1,
                virtualMachineSize: "Standard_NC6",
                virtualMachineConfiguration: new VirtualMachineConfiguration(
                    new ImageReference("ubuntu-server-container", "microsoft-azure-batch", "16-04-lts"),
                    "batch.node.ubuntu 16.04")
            {
                ContainerConfiguration = containerConfig
            });

            await pool.CommitAsync();
        }
Example #59
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("~/log4net.config")));
            ContainerConfiguration.Register(Server.MapPath("~/bin"));

            if (string.IsNullOrWhiteSpace(WitsmlSettings.OverrideServerVersion))
            {
                WitsmlSettings.OverrideServerVersion = typeof(EtpController).GetAssemblyVersion();
            }

            var container        = (IContainer)System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IContainer));
            var databaseProvider = container.Resolve <IDatabaseProvider>();

            // pre-init IWitsmlStore dependencies
            var store = container.Resolve <IWitsmlStore>();

            store.WMLS_GetCap(new WMLS_GetCapRequest(OptionsIn.DataVersion.Version141));

            Task.Run(async() =>
            {
                // Wait before initializing Hangfire to give server time to warm up
                await Task.Delay(WitsmlSettings.ChangeDetectionPeriod * 1000);

                var storageOptions = new MongoStorageOptions()
                {
                    MigrationOptions = new MongoMigrationOptions()
                    {
                        Strategy       = MongoMigrationStrategy.Migrate,
                        BackupStrategy = MongoBackupStrategy.None,
                    }
                };

                // Configure and register Hangfire jobs
                Hangfire.GlobalConfiguration.Configuration.UseMongoStorage(databaseProvider.ConnectionString, storageOptions);
                HangfireConfig.Register(container);
            });
        }
Example #60
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assemblyPath">Location where bootstrapped assemblies located</param>
        public void Compose(string assemblyPath)
        {
            // Catalogs does not exists in Dotnet Core, so you need to manage your own.
            var assemblies    = DiscoverAssemblies(assemblyPath, "VolleyM.");
            var configuration = new ContainerConfiguration()
                                .WithAssemblies(assemblies);

            using var container = configuration.CreateContainer();
            Bootstrappers       = container.GetExports <IAssemblyBootstrapper>().ToList();
            var bootstrappedAssemblies = new List <Assembly>();

            Console.WriteLine($"Discovered {Bootstrappers.Count} bootstrappers.");

            foreach (var bootstrapper in Bootstrappers)
            {
                bootstrappedAssemblies.Add(Assembly.GetAssembly(bootstrapper.GetType()));
            }

            DiscoveredAssemblies = bootstrappedAssemblies.ToImmutableList();
        }