MEF and windows10uwpmef under Windows 10 (UWP)

Source: Internet
Author: User
Tags log log

MEF and windows10uwpmef under Windows 10 (UWP)

  • Preface

Recently, I helped a well-known foreign company develop applications related to the Universal Windows Platform. There are two types of projects: one is the prefix, and the other is the one called the previous one. I don't want to talk about it anymore. I want to talk about it again and I want to talk about it again.

Let's talk about MEF.

MEF stands for Managed Extensibility Framework. We encounter Dependency Injection (DI: Dependency Injection) in. Net. We usually choose Unity or MEF, which is the two main methods used by Prism. Before. Net 4.0, MEF always existed as an extension, but it was already part of the Framework in. Net 4.0. However, MEF of. Net 4.0 is only the original version, and MEF 2 adds the wildcard class Import and Export features. MEF 2 does not act.. net 4.5 and later platforms, we can get this extension through Nuget, the source code is also hosted on the codeplex platform.

Microsoft Composition (MEF 2)

Source Code

Platforms supported by MEF2

- .NET Framework 4.5

- Windows 8

- Windows Phone 8.1

- Windows Phone Silverlight 8

- Portable Class Libraries

In general, when we talk about MEF, we generally describe it as a set of things for implementing plug-in development. When plug-in development becomes a possibility, it means that our project can be completely decoupled, which ensures the robustness of our program, at the same time, we also avoided conflicts between various developers during the development process.

  • Start

How do I start to write a MEF-based program?

Suppose we are writing a UWP project, and we use C # + XAML. MVVM is the main method of XAML. It can be used to bind data to an application. Therefore, MVVM is used.

Therefore, we decided to design a MVVM Mode Based on C # + XAML to decouple the View and ViewModel, in the middle, we can also implement a message transmission mode in the Observer mode to transmit parameters between views. It looks perfect. You can easily download an Mvvmlight for direct use.

We have decided on the View layer and ViewModel layer. What components are missing for a complete system? We can still lack data, so we need a data layer. We generally name it a Service layer to communicate with databases or servers. What else is missing? In the Log system, we need to perform some data statistics during the running process or the message record after exception capturing. Therefore, we need the Log layer and the cache layer, cache our data to the memory or disk, so that our program can run a little better.

After we decide, we need to write the following:

- View

- ViewModel

- Service

- Log

- Cache

How can we solve this problem?

public sealed class Hub{            public static Log Log { get; private set; }    public static Service Service { get; private set; }    public static Cache Cache { get; private set; }    private static Hub instance = null;    private static readonly object padlock = new object();    Hub()    {        Log = new Log();        Service = new Service();        Cache = new Cache();    }    public static Hub Instance    {        get        {            if (instance == null)            {                lock (padlock)                {                    if (instance == null)                    {                        instance = new Hub();                    }                }            }            return instance;        }    }}

The above solution introduces a single-instance Hub class, and each layer provides various functions as a read-only static attribute. It looks good and we can also call it well.

But there is a problem. When this class occurs, we do not want services and other classes to be instantiated externally. Unfortunately, when a Service is used as a Public attribute, the class itself is marked as Public for access consistency, this damages the original intention of setting up this class.

So how can we continue to solve this problem? The Service and other classes are designed as Singleton instances. This is also a solution. However, both this solution and the solution in the Code are strongly referenced, which means that the system will crash with a slight carelessness.

We do not want to introduce the Hub, nor do we want services and other classes to be designed as Singleton instances. In addition, we do not want specific Service instances in the ViewModel. What should we do?

Answer: dependency injection.

  • Redesign

Retain all the components we previously imagined and introduce interfaces to enter the injection:

- IService

- ILog

- ICache

Let's take a look at our ViewModel. What should we do now?

public class ViewModel{    ILog Log;    IService Service;    ICache Cache;    public ViewModel(ILog log, IService service, ICache cache)    {            Log = log;            Service = service;            Cache = cache;    }}

Next, we just need to call the instance we need. If we need a View, we can also declare an IView interface.

So far, we have not introduced MEF in our design, and it seems that we have relatively good decoupling. We only need to introduce specific instances when calling ViewModel, and coupling occurs here.

  • Introduce MEF

Imagine that since the objects of the instances we need to generate are already in our DLL, why do we need to manually generate an instance and then upload it to the specific constructor, cannot it be searched by itself?

Assume that all our classes have an alias, and then we will tell the program where we need to reference it. We need a class that implements the Ixxx interface. Its name is xxx, in this way, are we more involved. As follows:

public class ViewModel{    [Import("LogSample")]    ILog Log;    [Import("ServiceSample")]    IService Service;    [Import("CacheSample")]    ICache Cache;    public ViewModel()    {    }}

After the constructor is complete, Log and other objects will automatically find the implementation ILog class named LogSample in the program set. The same is true for Service and Cache.

Check the Log

[Export("LogSample", typeof(ILog))]public class Log : ILog{}

So far, we have focused on implementing specific functions.

  • MEF officially introduced

To simplify our program and focus more on the essence of MEF, we design the program to include only the following components

- View

- ViewModel

- Service

Create a project as follows:

[Export (Constant. confing. sampleService, typeof (IService)] public class SampleService: IService {public void QueryData (int numuber, Action <int> action) {action (numuber );}}

Let's take a look at the main interface of our program:

public sealed partial class MainPage : Page{    [Import(Constant.Confing.View1)]    public IView View1 { get; set; }    [Import(Constant.Confing.View2)]    public IView View2 { get; set; }    public MainPage()    {        this.InitializeComponent();        this.Loaded += MainPage_Loaded;    }    private CompositionHost host;    private void MainPage_Loaded(object sender, RoutedEventArgs e)    {        List<Assembly> assemblies = new List<Assembly>()        {            Assembly.Load(new AssemblyName("MEF.Service")),            Assembly.Load(new AssemblyName("MEF.View")),            Assembly.Load(new AssemblyName("MEF.ViewModel")),            Assembly.Load(new AssemblyName("MEF.Abstract"))            };        ContainerConfiguration configuration = new ContainerConfiguration().WithAssemblies(assemblies);        host = configuration.CreateContainer();        host.SatisfyImports(this);    }    private void View1_Click(object sender, RoutedEventArgs e)    {        IView view = host.GetExport(typeof(IView), Constant.Confing.View1) as IView;        frame.Content = view;    }    private void View2_Click(object sender, RoutedEventArgs e)    {        IView view = host.GetExport(typeof(IView), Constant.Confing.View2) as IView;        frame.Content = view;    }}

Add all the assembly to the container, and then create the object through the container.

View code:

[Export(Constant.Confing.View1,typeof(IView))]public sealed partial class View1 : UserControl, IView{    IService Service;    IViewModel ViewModel;    [ImportingConstructor]    public View1(        [Import(Constant.Confing.SampleService)]IService service,         [Import(Constant.Confing.ViewModel1)]IViewModel viewModel)    {        this.InitializeComponent();        this.Service = service;        this.ViewModel = viewModel;    }    private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)    {        Service.QueryData(ViewModel.Number, ShowValue);    }    private void ShowValue(int i)    {        Btn.Content = i;    }}
  • Demo

Initial status:

Summary

This article describes a simple reference of MEF under UWP, which demonstrates that MEF can better decouple the program through dependency injection. Read this article to help you.

Thank you ~

Code download: http://files.cnblogs.com/files/youngytj/uwp_MEF.zip

  • References:

Unity

MEF programming guide blog Summary

Prism

Relationship between Prism and MVVM, Unity, and MEF

Dependency Injection

System. Composition

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.