. NET 4 practices-using dynamic and MEF to implement lightweight AOP components (4)

Source: Internet
Author: User
Xianfo

We have introduced the structureDynamicAspectThe vast majority of classes, in order to makeAspectTo automatically implement it to the target object, we need to provide a dynamic load Aspect mechanism.DynamicAspectIn the initial version, the author uses the configuration file to provide a customDynamicAspectAnd then useXMLElement to describe eachAspectThe type of the program and the target type to be woven. The program is obtained through the configuration file during running.AspectAnd thenAspectLoad the object chain we designed. Configuration files do not have the advantage of other methods, that is, they can be dynamically woven. That is to say, when the demand changes, you only need to modify the configuration file, you do not need to recompile the main program or the original source code file, or even pause the running program. However, using a configuration file also has its disadvantages.XMLIt is inconvenient to check whether the values in the configuration file are correct, and the error tendency is large, and requires application developers and maintenance personnel to be familiarDynamicAspect. After careful evaluation, I decided to switchMEFTo achieve automatic search and automatic matching, andMEFThe built-in object lifecycle management mechanism can also be simplified.DynamicAspectThe architecture is briefly introduced below.MEF(For details, see the official MEF documentation ):

The full name of MEF isManaged Extensibility Framework(Managed scalable framework) when I first saw it, it was still at the MSDN site two years ago.Code GalleryIt migrated a year agoCodeplexIt becomes a permanent citizen of the. NET class library. It is said that various development teams within MS are responsible for developing various projects, and each team has its own set of extension frameworks. These extension frameworks are specific to their respective applications and are difficult to be reused by other teams, therefore, it is natural that MEF came forward to unify the chaotic world. Are teams busy integrating MEF now?

I don't know how many people knowMAF (Managed Add-in Framework), MAFIn. NET 3.5Is added to the class library. If you add System. AddIn. dll references to the project, you can see the namespace of System. AddIn.MSDNYou can find its introduction and usage in this document.MAF.MAFAndMEFThey are all added to the class library to support the development of scalable applications,MAFFocuses on Application Isolation and component loading and unloading, whileMEFMore attention can be paid to the aspects of discovery, scalability, and portability.MEFCan be summarized into three words:Export(Export ),Import(Import) andComposite(Combination ). In MEF, the objects involved in import and export becomePart(Component), in application,MEFA Host is required to store its root container. To discover the exported and imported parts, MEF designs several different Catalog classes to specify the range of the parts to be searched, for exampleTypeCatalogClass specifies the type of the part to be searched, andAssemblyCatalogIndicates the Assembly where the component to be searched is located,DirectoryCatalogSpecifies the file directory of the part to be searched.CatalogYou can useAggregateCatalogClasses are combined. In addition to the ability of MEF to automatically discover components through catalog, you can also explicitly callCompositePartThe Extension Method adds parts to the container. Let's take a look at the code.DynamicAspectHow to borrowMEFThis flower.

The first is the choice of the host. In the MEF example that can be found, the MEF host is placed on the side of the main running program. Considering that the main program may not be a MEF application, therefore, it is decided to create a container object in DynamicAspect. The container can be either the root container or a sub-container that is embedded into a parent container (if any ), in DynamicAspect, The IAspect interface is the part type to be processed, whether it is import or export. The process of instantiating a container part is carried out in the static class WeaverExtensiong:

   public static class WeaverExtension
   {

        public static CompositionContainer Container = null;

        static WeaverExtension()
        {
             AggregateCatalog catalog =new AggregateCatalog(
                                        new DirectoryCatalog(@".\"),
                                        new DirectoryCatalog(@".\", "*.exe"));

             Container = new CompositionContainer(catalog);
        }
 
        …
   }
 
This is a feature of static classes. A static class is initialized when the Assembly is loaded, and the static members are globally unique. Here, we define a MEFCompositionContainerContainer object, which is instantiated during assembly initialization. we specify MEF in the container to search for all the directories in the Assembly.DllFile andExeFile. The second parameter of the DirectoryCatalog constructor is used to specify the file to be matched. The default value is *. dll. A friend asked,MEFHow do I know what parts to search?IAspectWhat about the type? Good question, actuallyMEFI don't know. It just faithfully finds allExportAttributeOrImportAttributeAnd match according to the specified matching rules.DyanmaicAspectInAspectMatches the target type, but refers toExportAnd oneImportComponent matching.
Let's look back.AspectBaseClass Definition:
   [InheritedExport(typeof(IAspect))]
    public abstract class AspectBase : IAspect
   { … }
The feature applied here isInheritedExport,If yesExportAttributeBecauseExportAttributeDesigned to be unable to be applied to a derived class, all the derived classes must be declaredExportAttribute, MEF designers fully consider this and have prepared for usInheritedExportAttributeAs the name suggests, InheritedExport is the feature that can be passed along the inheritance chain.
Our Aspect is exported in this way. Where is the import? Do not worry. Import is defined in the WeavableObject class:
[ImportMany(typeof(IAspect), 
                    AllowRecomposition = true, 
                    RequiredCreationPolicy= CreationPolicy.Any)]
public IEnumerable<IAspect> Aspects { get; set; }
 
No, it's not here.ImportAttribute,ImportManyAttributeThis is becauseImportOnly import an object, while ourIAspectThere may be multiple, so we need to useImportManyThe two parameters in the feature are self-explanatory,AllowRecompositionIndicates that when a new type is imported, the parts in the container are re-matched. Every time a new Aspect object is imported, it is assembled into the AspectChain in time. we implementIPartImportsSatisfiedNotificationThis interface has only one method:
public void OnImportsSatisfied()
{
    var query = Aspects
                .Where(a => a.IsMatch(typeof(T).FullName) && a.Enabled == true)
                .OrderBy(a => a.Sequence);
          
    foreach (var asp in query)
             AddAspect(asp);
}
 
OnImportsSatisfied is triggered when the import meets a matching condition. The method code uses the LINQ query to filter out Aspect that cannot match the current target or that Enabled is equal to false.
The AddAspect method is as follows:
public void AddAspect(IAspect aspect)
{
    if (aspect != null)
    {
        lock (new object())
        {
            if (chain.FirstOrDefault(c =>
                  aspect.GetType().IsAssignableFrom(c.GetType())) == null)
               chain.AddLast(aspect);
        }
    }
}
A linq statement is used to prevent repeated assembly of the same object. The lock is for thread safety (this statement has been changed to lock (ICollection) chain). AynxRoot in new updates ))
DynamicAspectThe story may come to an end, but it is not over. DynamicAspect is still a seedling and needs to grow with everyone's care and care. At the same time, I encourage my friends to try DynamicAspect on different occasions. If you have any questions or suggestions, please reply here or send me feedback via email. Thank you first.

Finally, it should be noted that DynamicAspect is still under development and needs to be tested to prove its value. The author will continue to write the Growth Course of DynamicAspect as appropriate, I hope you will have more wonderful contributions.

(Full text)

 

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.