locked
Using MEF to satisfy imports from my MarkupExtension? RRS feed

  • Question

  • Hello dear community!

    I'm having a hard time trying to figure out how could I make a MarkupExtension with a [Import] property. I don't know how to inject my dependencies into it because my extension is not instanced by me, but by the own presentation core.

    My idea is to make a custom MarkupExtension that imports my own IResourceLocalizator, an injectable dependency that could provide strings for globalization from several resources (.resx, XAML, text files…, depending on the needs).

    I would like to avoid the use of the so-called ServiceLocator pattern. I heard it's actually an anti-pattern.

    Please, can you anybody help me out with this?

    BIG THANKS! 


    Desde España / From Spain


    Tuesday, September 25, 2012 9:47 PM

Answers

  • A service locator is not an anti-pattern, whoever said that is misinformed. You can only import things when MEF instantiates your class, there is no magic in dependency injection, if you new up your class, or WPF does, there is no opportunity for MEF to get involved to inject dependencies. Further there is not even any guarantee that your markup extension is running in the visual studio process, it could be running in an out of proc build process.

    Ryan

    Wednesday, September 26, 2012 4:41 PM

All replies

  • Is it so difficult? :(

    Desde España / From Spain

    Wednesday, September 26, 2012 7:43 AM
  • No, it's not. What that MarkupExtension does is inject a part. 

    What I want to do is that the extension itself have a property that is an [Import]. Since the instance of the markup extension is create by the presentation core, it doesn't resolve the imports and they remain null.

    Apart from that, the solution you propose has a ServiceLocator (MefLocator).

    Thanks anyways :) 


    Desde España / From Spain

    Wednesday, September 26, 2012 10:17 AM
  • A service locator is not an anti-pattern, whoever said that is misinformed. You can only import things when MEF instantiates your class, there is no magic in dependency injection, if you new up your class, or WPF does, there is no opportunity for MEF to get involved to inject dependencies. Further there is not even any guarantee that your markup extension is running in the visual studio process, it could be running in an out of proc build process.

    Ryan

    Wednesday, September 26, 2012 4:41 PM
  • Thanks a lot for your answer! After all, there's not effective reason to avoid a Service Locator pattern for it. I will try to build up my extension using it.

    Greetings and thanks again!


    Desde España / From Spain

    Sunday, September 30, 2012 8:02 PM