tags:

views:

135

answers:

1

Hi, Is it possible to inject an instance of the logger to every class that has a property of type ILogger using MEF. Is there any other solution that composing each class type indvidually. I tried looking up Batch composition but looks very tedious to me as every class that needs the logger instance needs to be composed in a batch. Is there any other good solution? Thanks in advance.

+4  A: 

Well, typically, in MEF, you allow MEF to do your object construction, which will allow it to automatically compose the objects correctly, and set the ILogger properties with [Import] tags automatically.

That being said, this doesn't always work in every scenario. If you cannot have MEF construct your objects because they're being generated from a separate source, there are other options.

For example, this common problem occurs in WPF and Silverlight. When you're using these technologies, you often want to allow the XAML parser to construct your objects, but in this case, they will never get composed.

Silverlight 4 is adding the CompositionInitializer class to handle this situation. What this allows you to do is just add this to your constructor:

public MyClass() // MyClass Constructor
{
    CompositionInitializer.SatisfyImports(this);
}

And the CompositionInitializer will use the catalogs defined in a static class named CompositionHost to compose the constructed object. This sounds like it might be a good alternative in your situation, as well...

Right now, there is not an "official" desktop version of this. Glenn Block posted an older port of this for desktop usage (named PartInitializer, which was the old name) to his SkyDrive, which works fairly well. It's quite easy to port the current SL version for use in desktop applications, though this would require manual porting.

That being said, it's been said (on twitter and elsewhere) that CompositionInitializer for Desktop usage will be added to the MEF codeplex site soon...

Reed Copsey
Thanks for the information. I've been running into the same problem coding a DataTemplateSelector and was thinking I might have to revert to passing around the specific context I needed through static properties. This way is cleaner.
Dan Bryant
What I want is to universally compose all imports exports within an application domain without having to compose dependencies in each class. Is this possible with MEF.
nitroxn
@nitroxn: No, not really. Exports are handled fine, but for imports, you have to explicitly compose objects - this provides a clean workaround which allows objects to compose themselves, but requires a single line addition to the object (which is importing)'s constructor.
Reed Copsey