You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
2.8 KiB
Markdown

3 years ago
# Guide on Managed Extensibility Framework (MEF)
- **Note:** Prism 7.2 and above dropped support for MEF. Prefered DI is Unity
- Microsoft ONLY partially port MEF to .NET Core as **Microsoft.Composition** [link](https://www.tutorialspoint.com/dotnet_core/dotnet_core_managed_extensibility_framework.htm#:~:text=You%20can%20use%20MEF%20in,Core%20as%20well%20but%20partially.)
- **Microsoft.Composition** [nuget](https://www.nuget.org/packages/Microsoft.Composition) is also deprecated as legacy
- [Microsoft](https://learn.microsoft.com/en-us/dotnet/framework/mef/)
- [Article 1](https://dailydotnettips.com/setting-up-policies-for-extensible-parts-in-mef/)
- [Article 2](https://www.codeproject.com/Articles/1266833/Let-s-Talk-about-MEF-Part-1)
- [Tim Corey](https://www.codeproject.com/Articles/376033/From-Zero-to-Proficient-with-MEF)
## Creation policy
- Three states of CreationPolicy :
- Shared : This means the object will be shared in the container for any other import statement. This is the default settings for any Export and content can associate with any other component.
- Non-Shared : This means the object will not be shared either directly or indirectly. This is used only when you do not want to share your object and risk being exposed to 3rd party libraries.
- Any : This settings will choose either shared or non-shared value.
- Creation Policy relationship of Import / Export
| Import / Export | Part.Any | Part.Shared | Part.NonShared |
|------------ |----------|-------------|----------------|
| Import.Any | Shared | Shared | Non Shared |
| Import.Shared | Shared | Shared | No Match |
| Import.NonShared | Non Shared | No Match | Non Shared |
## Converting MEF to Unity
- [Reference](http://songhayblog.azurewebsites.net/entry/2017-05-02-wpf-prism-migrating-from-mef-to-unity/)
- Steps
1. Replace MEF [Export] Attributes for Non-Views with Unity Statements
```cs
this._container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
```
2. Replace MEF [Export] Attributes for Navigation Views with Prism Statement
```cs
this._container.RegisterTypeForNavigation<FooView>();
```
3. Use Prism XAML Declarations for View-First Patterns
```xml
<UserControl x:Class="MyApp.Views.FooView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
```
4. Use the GetInstance() Anti-Pattern for View-Model-First Scenarios
```cs
this.GetInstance<IFooViewModel>();
this.GetInstance<IEditorViewModel>($"{nameof(FooView)}Model");
this.GetInstance<IEditorViewModel>($"{this.GetType().Name}Model");
```