How does the MEF DirectoryCatalog work?

DirectoryCatalog checks the assemblies in the directory to determine which classes are imported / exported. Any assemblies without import / export are not loaded.

This is an awesome feature, but how does it work? To examine custom attributes for types in an assembly, do you need to load the assembly? Once it is loaded, it cannot be unloaded, so it cannot be the way it works.

Is this something like AppDomain magic?

+6
source share
2 answers

Give it a try. DirectoryCatalog simply creates an AssemblyCatalog for each .dll file in a given directory. Because AssemblyCatalog calls AssemblyName.GetAssemblyName , non-.NET.dll files will not be loaded (an exception is thrown and placed inside AssemblyCatalog ). AssemblyCatalog calls Assembly.Load in the created AssemblyName . Thus, assemblies are loaded immediately when creating DirectoryCatalog . No magic, no AppDomains . But then it is well known that MEF loads assemblies in the current AppDomain . Use MAF if you want assemblies to be unloaded.

+10
source

This is an example of code that can help you.

 var directoryPath = "Dll folder path"; //Load parts from the available dlls in the specified path using the directory catalog var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll"); //Creating an instance of aggregate catalog. It aggregates other catalogs var aggregateCatalog = new AggregateCatalog(); aggregateCatalog.Catalogs.Add(directoryCatalog); //Crete the composition container var container = new CompositionContainer(aggregateCatalog); container.ComposeParts(this); [ImportMany] public List<IModule> Modules { get; set; } 
+1
source

Source: https://habr.com/ru/post/909410/


All Articles