Prism v4 + MEF + IValueConverter

Topics: Prism v4 - WPF 4
Nov 12, 2010 at 1:41 PM
Edited Nov 12, 2010 at 2:51 PM

Hello, I new to Prism and MEF. I'm trying to import the implementation of my service into a value converter.

Infrastructure Module


public
interface IService { void DoSometing(); } public class MyConverter : IValueConverter { private IService _service; [Import AllowDefault = true, AllowRecomposition = true] public IService Service { get; set ; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Service.DoSomething(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
Feature module

 

   [Export(typeof(IService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyService : IService
{
public void DoSomething() {}
}


On a view:
<Converters:MyConverer x:Key="myConverter />

<TextBlock Text={Binding MyProperty, Converter={StaticResource myConverter}} /> 

Unfortunately, the Service property on the value converter is always null.
Is this scenario possible?

Best regards

Nov 12, 2010 at 2:15 PM

Hi,

Nice to see that you started using Prism. Your scenario seems to be something possible. I checked the code that you shared and found the following:

   1. The Export attribute indicate a typeof ILookupService. So I assume that IService derives from ILookupService. Is this ok? or ILookupService should derive from IService. Anyway, I would suggest you to specify in the typeof the interface implemented in your class, in this particular case, the IService interface.
   2. If you decide to continue exporting ILookupService, I would recommend you to import ILookupService in the Service property in the MyConverter class.
   3. In the XAML code, the binding is targeting to MyProperty and it is not an existent property at MyConverter class.

Hope this helps.

Fernando Antivero
http://blogs.southworks.net/fantivero

Nov 12, 2010 at 2:58 PM

First, thanks for your fast reply.

Hi, I have edited my previous post. First, forget about the ILookupService it was a copy/paste mistake.
Secondly, MyProperty is a property of the ViewModel imported on the view.

Hope you could help.

 

 

Nov 12, 2010 at 6:52 PM

Hi,

A possible reason for this is that the converter is not created using the MEF container, so it does not inject your properties that are decorated with Import. So, if you need to achieve this scenario, you might need to create your converter programmatically with MEF.

But I was wondering if a converter is the correct place to call a service. That said, is not a view model the right place for doing something like this?

Hope this helps.

Fernando Antivero
http://blogs.southworks.net/fantivero