Below are my review notes from the 10-4 video on the upcoming Managed Extensibility Framework in version 4.0
namespace Sample { public interface IMortgageRateRepository { public IList GetCurrentRates(); } }
Notice that in the concrete implementation of the interface we use the Export Attribute
namespace Sample { [Export(typeof(IMortgageRateRepository))] public class ELoanMortgageRateRepository: IMortgageRateRepository { public IList GetCurrentRates() { return new List(); } } }
Alot of stuff happening here, we use the export attribute at the class level and then the Import attribute on our dependency. I also want to point out that we no longer 'new' up an object. Instead we implement the IPartImportsSatisfiedNotification interface and move out binding logic to that event handler (basically we can't use the objects until they have been imported by the container).
namespace Sample { [Export] public partial class MortgageRates: Window, IPartImportsSatisfiedNotification { [Import] IMortgageRateRepository MortgageRateRepository { get; set; } public MortgageRates() { InitializeComponent(); //MortgageRateRepository = new MortgageRateRepository(); //grid.ItemSource = MortgageRateRepository.GetCurrentRates(); } public void OnImportsSatisified() { Dispatcher.Invoke(new Action(() => { MortgageRateRepository = new MortgageRateRepository(); grid.ItemSource = MortgageRateRepository.GetCurrentRates(); })); } } }
Finally, where the magic happens. We create an AssemblyCatalog and then a CompositionContainer. Notice that instead of 'Newing' up an instance of the window directly. We get an instance of the exported object from the container.
namespace Sample { public partial class App: Application { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); var window = container.GetExportedObject<MortgageRates>(); //var window = new MortgageRates(); window.Show(); } }
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.