Monday, 19 August 2013

How to get DI to work in Prism/MEF with a simple class

How to get DI to work in Prism/MEF with a simple class

I understand how DI works in Prism when you have an IModule. However, many
of my classes where I want DI are not modules, they are plain old classes.
If I use the [Import] statement, I never see any injection occur. If I
decorate the class with IModule, I get injection. If anyone is familiar
with the Prism 4.1 Quickstarter, I'm using the 'ModularityWithMef.Desktop'
to demonstrate the problem. I've added this class to the 'ModuleA'
project:
Class1.cs:
namespace ModularityWithMef.Desktop
{
using System;
using System.ComponentModel.Composition;
using ModuleTracking;
public class Class1
{
private IModuleTracker moduleTrackerField;
[Import(typeof(IModuleTracker))]
public IModuleTracker ModuleTracker
{
get
{
return this.moduleTrackerField;
}
set
{
this.moduleTrackerField = value;
}
}
}
}
The setter is never hit. If I decorate it with an [Export] statement, I
can hit the setter, but then I get a message that I need to provide an
'Initialization()' method for any class decorated with an [Export]
attribute. What am I missing here? I see the advantage of using attribute
based DI, but I can't imagine that I have to turn every class I use into
an IModule.

No comments:

Post a Comment