public void ModuleInUnreferencedAssemblyInitializedByModuleInitializer() { AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll()); CompositionContainer compositionContainer = new CompositionContainer(assemblyCatalog); ModuleCatalog moduleCatalog = new ModuleCatalog(); Mock<MefFileModuleTypeLoader> mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>(); compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog); compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object); bool wasInit = false; var mockModuleInitializer = new Mock<IModuleInitializer>(); mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true); var mockLoggerFacade = new Mock<ILoggerFacade>(); MefModuleManager moduleManager = new MefModuleManager( mockModuleInitializer.Object, moduleCatalog, mockLoggerFacade.Object); compositionContainer.SatisfyImportsOnce(moduleManager); moduleManager.Run(); Assert.IsTrue(wasInit); }
private void AddAssemblies(ContainerBuilder builder) { var directory = @".\Application_1"; //var directory = @".\Application_2"; var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories); foreach (var file in files) { try { var asmCat = new AssemblyCatalog(file); if (asmCat.Parts.ToList().Count > 0) { builder.RegisterComposablePartCatalog(asmCat); } } catch (ReflectionTypeLoadException) { } catch (BadImageFormatException) { } } }
private static CompositionContainer CreateCompositionContainer() { ComposablePartCatalog catalog; var extensionsPath = GetExtensionsPath(); // If the extensions folder exists then use them if (Directory.Exists(extensionsPath)) { catalog = new AggregateCatalog( new AssemblyCatalog(typeof(Bot).Assembly), new AssemblyCatalog(typeof(Program).Assembly), new DirectoryCatalog(extensionsPath, "*.dll")); } else { catalog = new AssemblyCatalog(typeof(Bot).Assembly); } return(new CompositionContainer(catalog)); }
/// <summary> /// 统一导入点 /// </summary> /// <param name="target"></param> /// <returns></returns> public static CompositionContainer Satisfy(object target = null) { if (container == null) { DirectoryCatalog dirCatalog = new DirectoryCatalog("."); AssemblyCatalog assemblyCat = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()); AggregateCatalog catalog = new AggregateCatalog(assemblyCat, dirCatalog); container = new CompositionContainer(catalog); } if (target != null) { container.SatisfyImportsOnce(target); } else { container.ComposeParts(); } return(container); }
/// <summary> /// Creates the container. /// </summary> /// <remarks>This method is called on a different thread to speed up startup.</remarks> /// <returns></returns> private static CompositionContainer CreateContainer() { var entryAssembly = Assembly.GetEntryAssembly(); var assemblyCatalog = new AssemblyCatalog(entryAssembly); var location = entryAssembly.Location; var directory = new FileInfo(location).DirectoryName; var directoryCatalog = new DirectoryCatalog(directory, "*.dll"); var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog); //Subdirectories. var directories = Directory.GetDirectories(directory, "*", SearchOption.AllDirectories); foreach (var catalog in directories.Select(x => new DirectoryCatalog(x, "*.dll"))) { aggregateCatalog.Catalogs.Add(catalog); } return(new CompositionContainer(aggregateCatalog)); }
public static void Main(string[] args) { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); using (CompositionContainer container = new CompositionContainer(catalog)) { IApplication application = container.GetExportedValue <IApplication>(); application.Args = new Dictionary <string, string>(); if (args.Length > 0) { foreach (var arg in args[0].Split('|')) { var split = arg.Split('='); application.Args.Add(split[0], split[1]); } } application.Start(); } }
void AddAssemblyCatalog(string file) { var fileExt = EngineNS.CEngine.Instance.FileManager.GetFileExtension(file); if (fileExt == "dll") { try { if (!AssemblyCatalogExist(file)) { file = file.Replace("/", "\\"); var cata = new AssemblyCatalog(System.Reflection.Assembly.LoadFrom(file)); mCatalog.Catalogs.Add(cata); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } }
public static void Run() { var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var compositionContainer = new CompositionContainer(assemblyCatalog); var example = new MetadataExample(); compositionContainer.ComposeParts(example); foreach (Lazy <string, IMetadata> text in example.imported) { if (text.Metadata.text == "Yes") { Console.WriteLine(text.Value.ToUpper()); } else { Console.WriteLine(text.Value); } } }
public void Export_provider_can_resolve_service_registered_by_type_and_registration_name() { // Setup var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var provider = new FactoryExportProvider(FactoryMethod1); var container = new CompositionContainer(assemblyCatalog, provider); // Registration provider.Register(typeof(IExternalComponent), "external2"); var externalComponent = container.GetExportedValue <IExternalComponent>("external2"); Assert.That(externalComponent, Is.Not.Null); Assert.That(externalComponent.GetType(), Is.EqualTo(typeof(ExternalComponent2))); var mefComponent = container.GetExportedValue <IMefComponent>("component2"); Assert.That(mefComponent, Is.Not.Null); Assert.That(mefComponent.Component1.GetType(), Is.EqualTo(typeof(ExternalComponent2))); Assert.That(mefComponent.Component2.GetType(), Is.EqualTo(typeof(ExternalComponent2))); }
public void AssembleCalculatorComponents() { try { var aggregateCatalog = new AggregateCatalog(); var directoryPath = @"d:\lib"; var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll"); var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); aggregateCatalog.Catalogs.Add(directoryCatalog); aggregateCatalog.Catalogs.Add(asmCatalog); var container = new CompositionContainer(aggregateCatalog); container.ComposeParts(this); } catch (Exception ex) { throw ex; } }
/// <summary> /// Assembles the calculator components /// </summary> public void AssembleCalculatorComponents() { try { //Step 1: Initializes a new instance of the // System.ComponentModel.Composition.Hosting.AssemblyCatalog class with the // current executing assembly. var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); //Step 2: The assemblies obtained in step 1 are added to the CompositionContainer var container = new CompositionContainer(catalog); //Step 3: Composable parts are created here i.e. the Import and Export components // assembles here container.ComposeParts(this); } catch (Exception ex) { throw ex; } }
public PerformanceTestCoordinator() { Bridge = new HaywireBridge(FileName, HaywireStartUpMode.PerformanceTest); AggregateCatalog catalog = new AggregateCatalog(); AssemblyCatalog assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly); // DirectoryCatalog directoryCatalog = new DirectoryCatalog(".", "Library*.dll"); // catalog.Catalogs.Add(directoryCatalog); catalog.Catalogs.Add(assemblyCatalog); this.Container = new CompositionContainer(catalog); //CompositionBatch batch = new CompositionBatch(); //batch.AddExportedValue(this.Container); // this.Container.Compose(batch); this.Container.ComposeParts(this); }
private void setupPlugins() { // 1. Populate all the plugins from disk into the property 'filenames' AggregateCatalog ag = new AggregateCatalog(); DirectoryCatalog dc = new DirectoryCatalog(@"."); // Reads the Plugins from the folder where the executable resides ag.Catalogs.Add(dc); AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(ag); container.SatisfyImportsOnce(this); // 'SatisfyImportsOnce' means hook everything up at once // 2. Now we have all the plugins data, populate the 'DeletionMethods' property foreach (ITextToFilenames ttf in this.filenames) { DeletionMethod dm = new DeletionMethod(ttf.Title, ttf.Description, ttf.GetFilenames); dm.CheckForFilesClicked += CheckForFilesClicked; deletionMethods.Add(dm); } }
public void Compose() { try { var first = new AssemblyCatalog(Assembly.GetExecutingAssembly()); catalog = new AggregateCatalog(first); container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddExportedValue <IFileSystem>(new FileSystem()); batch.AddPart(this); container.Compose(batch); } catch (ReflectionTypeLoadException ex) { Console.WriteLine(@"Unable to load: \r\n{0}", string.Join("\r\n", ex.LoaderExceptions.Select(e => e.Message))); throw; } }
/// <summary> /// Gets the dependency resolver. /// </summary> /// <param name="config">The configuration.</param> /// <returns>MefDependencyResolver.</returns> private MefDependencyResolver GetDependencyResolver(HttpConfiguration config) { Log.Info("Looking for MEF components"); var executingAssemblyFile = Assembly.GetExecutingAssembly().Location; var executingDirectory = Path.GetDirectoryName(executingAssemblyFile); var mcFlyAssemblies = Directory.EnumerateFiles(executingDirectory, "McFly*.dll", SearchOption.AllDirectories); var assemblies = mcFlyAssemblies.Select(Assembly.LoadFile).Select(a => new AssemblyCatalog(a)); var executingAssembly = Assembly.GetExecutingAssembly(); var executingAssemblyCatalog = new AssemblyCatalog(executingAssembly); var aggregateCatalog = new AggregateCatalog(assemblies.Concat(new[] { executingAssemblyCatalog })); var compositionContainer = new CompositionContainer(aggregateCatalog); var settings = new Settings { ConnectionString = "Data Source=localhost;Integrated Security=true" }; compositionContainer.ComposeExportedValue(settings); var mefDependencyResolver = new MefDependencyResolver(compositionContainer, config.DependencyResolver); return(mefDependencyResolver); }
public void MefCanResolveLazyTypeRegisteredInUnityTest() { // Setup var unityContainer = new UnityContainer(); var adapter = new UnityContainerAdapter(unityContainer); var provider = new ContainerExportProvider(adapter); var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(assemblyCatalog, provider); UnityOnlyComponent1.InstanceCount = 0; unityContainer.RegisterType <IUnityOnlyComponent, UnityOnlyComponent1>(); var lazyUnityComponent = container.GetExport <IUnityOnlyComponent>(); Assert.That(lazyUnityComponent, Is.Not.Null); Assert.That(UnityOnlyComponent1.InstanceCount, Is.EqualTo(0)); Assert.That(lazyUnityComponent.Value, Is.Not.Null); Assert.That(lazyUnityComponent.Value.GetType(), Is.EqualTo(typeof(UnityOnlyComponent1))); Assert.That(UnityOnlyComponent1.InstanceCount, Is.EqualTo(1)); }
public MefHost(string folderPlugins) { List <DirectoryCatalog> lstPluginsDirCatalogs = new List <DirectoryCatalog>(); string[] subFolders = System.IO.Directory.GetDirectories(folderPlugins); foreach (var subFolder in subFolders) { var dirCat = new DirectoryCatalog(subFolder, "*plugin*.dll"); lstPluginsDirCatalogs.Add(dirCat); } var assem = System.Reflection.Assembly.GetExecutingAssembly(); var catThisAssembly = new AssemblyCatalog(assem); var catAgg = new AggregateCatalog(lstPluginsDirCatalogs); catAgg.Catalogs.Add(catThisAssembly); var compose = new CompositionContainer(catAgg); this.Parent = this; compose.ComposeParts(this); }
public void Compose() { Thread tr = new Thread(() => { dirCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory); AssemblyCatalog assemblyCat = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()); AggregateCatalog catalog = new AggregateCatalog(assemblyCat, dirCatalog); CompositionContainer container = new CompositionContainer(catalog); try { container.ComposeParts(this); } catch (Exception) { } OnPluginsLoaded(); }); tr.Start(); }
void Inner() { using (var catalog = new AssemblyCatalog(GetType().Assembly)) using (var container = new CompositionContainer(catalog)) { container.ComposeExportedValue(this); container.ComposeExportedValue(BuildEngine); container.ComposeExportedValue(logger); CheckForInvalidConfig(); container.GetExportedValue <TargetPathFinder>().Execute(); logger.LogMessage(string.Format("\tTargetPath: {0}", TargetPath)); container.GetExportedValue <AssemblyResolver>().Execute(); var moduleReader = container.GetExportedValue <ModuleReader>(); moduleReader.Execute(); var fileChangedChecker = container.GetExportedValue <FileChangedChecker>(); if (!fileChangedChecker.ShouldStart()) { return; } container.GetExportedValue <MsCoreReferenceFinder>().Execute(); container.GetExportedValue <AssemblyLoaderImporter>().Execute(); container.GetExportedValue <ModuleLoaderImporter>().Execute(); container.GetExportedValue <DependencyFinder>().Execute(); container.GetExportedValue <ProjectKeyReader>().Execute(); container.GetExportedValue <ResourceCaseFixer>().Execute(); using (var resourceEmbedder = container.GetExportedValue <ResourceEmbedder>()) { resourceEmbedder.Execute(); var savePath = GetSavePath(); container.GetExportedValue <ModuleWriter>().Execute(savePath); } container.GetExportedValue <ReferenceDeleter>().Execute(); } }
private AggregateCatalog CreateCatalog(string folderInAppData, List <string> pluginsToIgnore = null) { mExternalAssemblies.Clear(); LoadReferenceLists(); var returnValue = new AggregateCatalog(); var pluginDirectories = GetPluginDirectories(folderInAppData); foreach ( var directory in pluginDirectories) { AddPluginsFromDirectory(pluginsToIgnore, returnValue, directory); } if (mGlobal) { Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly(); var newCatalog = new AssemblyCatalog(executingAssembly); returnValue.Catalogs.Add(newCatalog); Assembly entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); if (entryAssembly != executingAssembly && entryAssembly != null) { newCatalog = new AssemblyCatalog(entryAssembly); returnValue.Catalogs.Add(newCatalog); } foreach (var assembly in AddGlobalOnInitialize) { newCatalog = new AssemblyCatalog(assembly); returnValue.Catalogs.Add(newCatalog); } } return(returnValue); }
protected override void ConfigureAggregateCatalog() { //var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var assemblyCatalog = new AssemblyCatalog(typeof(MyBootstrapper).Assembly); AggregateCatalog.Catalogs.Add(assemblyCatalog); assemblyCatalog = new AssemblyCatalog(typeof(ViewOneModule.ModuleOne).Assembly); AggregateCatalog.Catalogs.Add(assemblyCatalog); assemblyCatalog = new AssemblyCatalog(typeof(ViewTwoModule.ModuleTwo).Assembly); AggregateCatalog.Catalogs.Add(assemblyCatalog); assemblyCatalog = new AssemblyCatalog(typeof(ViewThreeModule.ModuleThree).Assembly); AggregateCatalog.Catalogs.Add(assemblyCatalog); assemblyCatalog = new AssemblyCatalog(typeof(ViewFourModule.ModuleFour).Assembly); AggregateCatalog.Catalogs.Add(assemblyCatalog); base.ConfigureAggregateCatalog(); }
public void MefCanResolveTypesRegisteredInUnityAfterTrackingExtensionIsAddedTest() { // Setup var unityContainer = new UnityContainer(); // Enable tracking TypeRegistrationTrackerExtension.RegisterIfMissing(unityContainer); // Registration unityContainer.RegisterType <IUnityOnlyComponent, UnityOnlyComponent2>("unityComponent2"); // Further setup var adapter = new UnityContainerAdapter(unityContainer); var provider = new ContainerExportProvider(adapter); var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(assemblyCatalog, provider); var component = container.GetExportedValue <IUnityOnlyComponent>("unityComponent2"); Assert.That(component, Is.Not.Null); Assert.That(component.GetType(), Is.EqualTo(typeof(UnityOnlyComponent2))); }
public SafeDirectoryCatalog(string directory) { var files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories); _catalog = new AggregateCatalog(); foreach (var file in files) { try { var asmCat = new AssemblyCatalog(file); if (asmCat.Parts.ToList().Count > 0) { _catalog.Catalogs.Add(asmCat); } } catch (ReflectionTypeLoadException) { } } }
/// <summary> /// Assembles the calculator components /// </summary> public void AssembleCalculatorComponents() { try { //Creating an instance of aggregate catalog. It aggregates other catalogs var aggregateCatalog = new AggregateCatalog(); //Build the directory path where the parts will be available var directoryPath = string.Concat(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) .Split('\\').Reverse().Skip(3).Reverse().Aggregate((a, b) => a + "\\" + b) , "\\"); var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); Func <string, DirectoryCatalog> getDirCatalog = (x => { return(new DirectoryCatalog(System.IO.Path.Combine(directoryPath, x), "*.dll")); }); //Load parts from the available dlls in the specified path using the directory catalog //Load parts from the current assembly if available //Add to the aggregate catalog aggregateCatalog.Catalogs.Add(asmCatalog); aggregateCatalog.Catalogs.Add(getDirCatalog("Add/bin/Debug")); aggregateCatalog.Catalogs.Add(getDirCatalog("Subtraction/bin/Debug")); //Crete the composition container var container = new CompositionContainer(aggregateCatalog); // Composable parts are created here i.e. the Import and Export components assembles here container.ComposeParts(this); } catch (Exception ex) { throw ex; } }
/// <summary> /// Gets the assemblies. /// </summary> /// <returns></returns> private static IList <Assembly> GetAssemblies() { var result = new List <Assembly>(); var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll", SearchOption.TopDirectoryOnly).ToList(); // Load current execuable file files.Add(Assembly.GetExecutingAssembly().Location); // Load external dll foreach (var file in files) { var ass = Assembly.LoadFile(file); using (var assemblyCatalog = new AssemblyCatalog(ass)) { if (assemblyCatalog.Parts.Any()) { result.Add(ass); } } } return(result); }
/// <summary> /// Initializes a new instance of the <see cref="SafeDirectoryCatalog"/> class. /// </summary> /// <param name="baseType">Type of the base.</param> public SafeDirectoryCatalog(Type baseType) { var assemblies = Reflection.GetPluginAssemblies(); // Add Rock.dll assemblies.Add(typeof(SafeDirectoryCatalog).Assembly); string baseTypeAssemblyName = baseType.Assembly.GetName().Name; _catalog = new AggregateCatalog(); foreach (var assembly in assemblies.ToList()) { try { // only attempt to load the catalog if the assembly is or references the basetype assembly if (assembly == baseType.Assembly || assembly.GetReferencedAssemblies().Any(a => a.Name.Equals(baseTypeAssemblyName, StringComparison.OrdinalIgnoreCase))) { AssemblyCatalog assemblyCatalog = new AssemblyCatalog(assembly); // Force MEF to load the plugin and figure out if there are any exports // good assemblies will not throw the RTLE exception and can be added to the catalog if (assemblyCatalog.Parts.ToList().Count > 0) { _catalog.Catalogs.Add(assemblyCatalog); } } } catch (ReflectionTypeLoadException e) { foreach (var loaderException in e.LoaderExceptions) { Rock.Model.ExceptionLogService.LogException(new Exception("Unable to load MEF from " + assembly.FullName, loaderException)); } string msg = e.Message; } } }
/// <summary> /// Build MEF catalog and create composition container /// </summary> /// <returns>Configured composition container</returns> private CompositionContainer CreateCompositionContainer() { // In addition to explicitly exported classes, auto-export all web api controllers var rb = new RegistrationBuilder(); rb.ForTypesMatching <ApiController>(t => typeof(ApiController).IsAssignableFrom(t) && t.Name.EndsWith("Controller")) .Export() .SetCreationPolicy(CreationPolicy.NonShared); var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb); // Create composition container var container = new CompositionContainer(catalog); container.ComposeExportedValue <INameGenerator>(new NameGenerator()); container.ComposeExportedValue(new BooksDemoDataOptions { MinimumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MinimumNumberOfBooks"]), MaximumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MaximumNumberOfBooks"]) }); return(container); }
public void MefResolvesServiceRegisteredInUnityByTypeTest() { // Setup var unityContainer = new UnityContainer(); var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); // Register catalog and types unityContainer.RegisterCatalog(assemblyCatalog); // Registration unityContainer.RegisterType <IUnityOnlyComponent, UnityOnlyComponent1>(new ContainerControlledLifetimeManager()); var container = unityContainer.Resolve <CompositionContainer>(); var unityOnlyComponent = container.GetExportedValue <IUnityOnlyComponent>(); var unityOnlyComponent2 = unityContainer.Resolve <IUnityOnlyComponent>(); Assert.That(unityOnlyComponent, Is.Not.Null); Assert.That(unityOnlyComponent.GetType(), Is.EqualTo(typeof(UnityOnlyComponent1))); Assert.That(unityOnlyComponent2, Is.Not.Null); Assert.That(unityOnlyComponent2.GetType(), Is.EqualTo(typeof(UnityOnlyComponent1))); Assert.That(unityOnlyComponent, Is.EqualTo(unityOnlyComponent2)); }
private void Application_Startup(object sender, StartupEventArgs e) { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(this); if (this.BookServices != null) { foreach (var s in this.BookServices) { MessageBox.Show(s.GetBookName()); } } if (this.InputString != null) { foreach (var str in this.InputString) { MessageBox.Show(str); } } //调用无参数方法 if (this.methodWithoutPara != null) { MessageBox.Show(this.methodWithoutPara()); } //调用有参数方法 if (this.methodWithPara != null) { MessageBox.Show(this.methodWithPara(3000)); } MainWindow window = new MainWindow(); window.Show(); }
public void DisposingAutofacDisposesCompositionContainerTest() { // Setup var builder = new ContainerBuilder(); builder.EnableCompositionIntegration(); var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); // Add composition support for autofac builder.EnableCompositionIntegration(); builder.RegisterCatalog(assemblyCatalog); var autofacContainer = builder.Build(); var compositionContainer = autofacContainer.Resolve <CompositionContainer>(); autofacContainer.Dispose(); Assert.That(delegate { compositionContainer.GetExport <IMefComponent>(); }, Throws.TypeOf <ObjectDisposedException>()); }
public void AutofacCanResolveMultipleMefInstancesTest() { // Setup var builder = new ContainerBuilder(); builder.EnableCompositionIntegration(); var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); // Add composition support for autofac builder.EnableCompositionIntegration(); builder.RegisterCatalog(assemblyCatalog); var autofacContainer = builder.Build(); Assert.That(delegate { var defaultInstance = autofacContainer.Resolve <IMultipleMefComponent>(); Debug.WriteLine("Default Instance -> {0}", defaultInstance); var all = autofacContainer.Resolve <IEnumerable <IMultipleMefComponent> >().ToArray(); Debug.WriteLine("All instances -> {0}, {1}", all); }, Throws.Nothing); }
private void Compose() { AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog); //container.SatisfyImportsOnce(catalog.CreateCompositionService()); }
public void DeclaredModuleWithTypeInUnreferencedAssemblyIsUpdatedWithTypeNameFromExportAttribute() { AggregateCatalog aggregateCatalog = new AggregateCatalog(); CompositionContainer compositionContainer = new CompositionContainer(aggregateCatalog); var mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>(); mockFileTypeLoader.Setup(tl => tl.CanLoadModuleType(It.IsAny<ModuleInfo>())).Returns(true); ModuleCatalog moduleCatalog = new ModuleCatalog(); ModuleInfo moduleInfo = new ModuleInfo { ModuleName = "MefModuleOne", ModuleType = "some type" }; moduleCatalog.AddModule(moduleInfo); compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog); compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object); bool wasInit = false; var mockModuleInitializer = new Mock<IModuleInitializer>(); mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true); var mockLoggerFacade = new Mock<ILoggerFacade>(); MefModuleManager moduleManager = new MefModuleManager( mockModuleInitializer.Object, moduleCatalog, mockLoggerFacade.Object); compositionContainer.SatisfyImportsOnce(moduleManager); moduleManager.Run(); Assert.IsFalse(wasInit); AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll()); aggregateCatalog.Catalogs.Add(assemblyCatalog); compositionContainer.SatisfyImportsOnce(moduleManager); mockFileTypeLoader.Raise(tl => tl.LoadModuleCompleted += null, new LoadModuleCompletedEventArgs(moduleInfo, null)); Assert.AreEqual("MefModulesForTesting.MefModuleOne, MefModulesForTesting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", moduleInfo.ModuleType); Assert.IsTrue(wasInit); }