Prism MEF example

These attributes are under namespace System.ComponentModel.Composition

  • Import
    The attribute can be used on fields, properties, parameters. E.g. If a property is defined with the attribute, the property will be created automatically when the object is created.
    Example:
        [Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
        public EmployeeGridViewModel Model
        {
            get
            {
                return this.Owner.DataContext as EmployeeGridViewModel;
            }
            set
            {
                this.Owner.DataContext = value;
            }
        }
  • ImportingConstructor
    For previous example, how to create an instance of EmployeeGridViewModel? It will need attribute ImportingConstructor.
        [ImportingConstructor]
        public EmployeeGridViewModel(IEmployeeService employeeService)
        {
            this.employeeService = employeeService;
            ...
        }
  • Export: This attribute is used to register a class into MEF.
    Next question is how to create an instance of IEmployeeService, look this:
    [Export(typeof(IEmployeeService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class EmployeeService : IEmployeeService
    {
        
    }

These code registers EmployeeService as an impelement of type IEmployeeService.

  • PartCreationPolicy
    The attribtue is used with attribute Export, tell MEF the class creation policy, implment a singleton policy or create an instance always.
非常感谢阅读!如有不足之处,请留下您的评价和问题。
请“推荐”本文!
原文地址:https://www.cnblogs.com/steven-yang/p/5153742.html