I have tried searching for this from other posts, but was not able to find an answer, so creating a new question.
I am building an ETL system.
Now I have a class which has the following Imports:
[Import]
public IDataExtractor DataExtractor { get; set; }
[Import]
public IDataTransformer DataTransformer { get; set; }
[Import]
public IDataValidator DataValidator { get; set; }
[Import]
public IDataPublisher DataPublisher { get; set; }
[Import]
public IDataUpdater DataUpdater { get; set; }
My program.cs has the following code for composition:
var catalog = new AggregateCatalog();
if (!string.IsNullOrEmpty(ConfigKeys["Extractor"]))
catalog.Catalogs.Add(new DirectoryCatalog(ConfigKeys["Extractor"]));
if (!string.IsNullOrEmpty(ConfigKeys["Transformer"]))
catalog.Catalogs.Add(new DirectoryCatalog(ConfigKeys["Transformer"]));
if (!string.IsNullOrEmpty(ConfigKeys["Validator"]))
catalog.Catalogs.Add(new DirectoryCatalog(ConfigKeys["Validator"]));
if (!string.IsNullOrEmpty(ConfigKeys["Publisher"]))
catalog.Catalogs.Add(new DirectoryCatalog(ConfigKeys["Publisher"]));
if (!string.IsNullOrEmpty(ConfigKeys["Updater"]))
catalog.Catalogs.Add(new DirectoryCatalog(ConfigKeys["Updater"]));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
Where ConfigKeys[] is my config management system, where I can specify, the path of the dll for each extractor, transformer, Validator, etc.
The full process is: Extraction, Transformation, Validation, Publish, Updating.
Certain times, all that is require are 3 functions to be executed: Extraction, Transformation,Publish. So if the Config system, does not have a path for the Validator dll, I dont want an instance of the IDataValidator interface. But if I specify a blank, I get an error during composition.
Error: The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 4 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information. "The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.\r\n\r\n1) No exports were found that match the constraint: \n\tContractName\tCTP.DCU.Models.Interfaces.IDataTransformer\n\tRequiredTypeIdentity\tCTP.DCU.Models.Interfaces.IDataTransformer\r\n"
My question is: For every IMPORT, I may not have an EXPORT and I want to handle that gracefully. Is there a way to do that in MEF? How can I handle this scenario? I thought of creating empty dummy stubs for substituting, but really is that what everyone does?
Thank you!
If you want to make an [Import]
optional, you can use AllowDefault
:
[Import(AllowDefault = true)]
public IDataTransformer DataTransformer { get; set; }
If there is no matching [Export]
then the DataTransformer
property will be left null
.