(转)MEF+Unity

http://www.dotnetspark.com/kb/4659-mef--unity-interception.aspx

MEF + Unity Interception

Posted By:Mahadesh Mahalingappa       Posted Date: August 06, 2011    Points: 200    Category: C#    URL:

In this article I try to use MEF with Unity Framework . I am trying to build a simple app which would be extensible and at the same time would use Aspect Oriented Concept

 

Scope of this Article

In this article, I try to use MEF with Unity Framework. I am trying to build a simple app which would be extensible and at the same time would use Aspect Oriented Concept.

Prerequisites

Basic knowledge of MEF and Unity framework.

Step 1

A. Download the MEF Contrib from the site - http://mefcontrib.codeplex.com/

Question to be asked is why should you download MEF Contrib when you already have MEF DLLs with you. Well, the MEF DLLs do not provide us the Layer which integrates with the Unity Framework. Hence MEF Components cannot be accessed by Unity Framework and vice versa.

B. Download the Unity Application Block DLLs from the site -http://www.microsoft.com/download/en/details.aspx?id=9093

Once we have the DLLs downloaded, we can start with coding. Before coding, let‘s get some understanding of what we are trying here.
We are going to use MEFContrib to provide an extensibility to our application and Unity Framework so that we can bring the concept of Aspect Oriented Programming.

Unity + MEF Integration Layer is a middle component (implemented as MefContrib.Integration.Unity.dll) that combines the strength of both frameworks and allows great extensibility. Using integration layer, the developer can structure the application‘s backbone using Unity while leaving the extensibility part to MEF as you can see from the figure below:

What the layer actually does is that it makes MEF components (i.e. components known to MEF) available to the Unity by automatically injecting them into Unity components (i.e., components registered in the Unity container), and vice versa. This "synchronization" can be either one-way or two way. In the first case, Unity will know about MEF components (but MEF will know nothing about Unity), thus Unity will be able to inject MEF components into Unity ones. The opposite synchronization, in which MEF will know about Unity‘s components, is also possible but is unlikely to be used. In the second scenario, both MEF and Unity know about each other, enabling both frameworks to use each other components.

Step 2

I have added all the DLLs and dependency DLLs (not necessary to add as references) required for this application as shown below:

Step 3

public interface ILogger
    {
        void Write(string message);
    }

Creating the Console Logger

using System.ComponentModel.Composition;

  [Export(typeof(ILogger))]

    public class ConsoleLogger : ILogger
    {
        public void Write(string message)
        {
            Console.WriteLine(message);
        }
    }

Creating the Interceptor

The Interceptor code would look like below:

using Microsoft.Practices.Unity.InterceptionExtension;
using System.ComponentModel.Composition;

public class Interceptor : IInterceptionBehavior
    {
        [Import]
        public ILogger Logger { get; set; }

        public Interceptor()
        {
        }

        public IEnumerable GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
            //return null;
        }

        public IMethodReturn Invoke
        (IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {

            IMethodReturn msg = null;

            //Pre method calling
            Logger.Write("Hello World + Pre Method Calling");

           // Method is invoked
            msg = getNext()(input, getNext);

            //Post method calling
            Logger.Write("Hello World + Post Method Calling");

            return msg;
        }

        public bool WillExecute
        {
            get
            {
                return true;
            }
        }
    } 

Create an Interface for the Application class.

public interface IApplication
    {
        void Run();
    }

Application class looks as below:

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

public class Application : IApplication
    {
        [Import]
        public ILogger Logger { get; set; }

        public virtual void Run()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);

            container.ComposeParts(this);

            Logger.Write("Helloworld");
            Console.ReadLine();
        }
    }

Final Structure

 Let‘s give it a run:

Using Interception with Unity

Interception is a design pattern that is designed for cross-cutting concerns, issues that cut across the entire software. You can intercept a method call after the method call has been made. In short, it‘s a method of achieving Aspect Oriented Programming.

Unity provides support for interception through the Interception container extension.
To get an insight into what Interception is, check out this link.

VirtualMethodInterceptor

A type interceptor. It uses dynamic code generation to create a derived class that gets instantiated instead of the original, intercepted class and to hook up the call handlers.

Use

Let‘s discuss about the Interceptor which is the key component.
Interceptor is a class which implements the interface Microsoft.Practices.Unity.InterceptionExtension.IInterceptionBehavior.

IInterceptionBehavior

namespace Microsoft.Practices.Unity.InterceptionExtension
{
    public interface IInterceptionBehavior
    {
        bool WillExecute { get; }

        IEnumerable GetRequiredInterfaces();
        IMethodReturn Invoke(IMethodInvocation input,
			GetNextInterceptionBehaviorDelegate getNext);
    }
}

Resolving the Dependencies for the Unity Container

When a call is made to the Resolve method on the Unity container, dependencies are fetched using theGetRequiredInterfaces() method. So this method acts as a Dependency Resolver.

public IEnumerable GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

Turning the Interceptor On and Off

This property lets the Interceptor know whether it has to intercept the method call or not. If WillExecute istrue, the interceptor would be activated, a false would deactivate the interceptor.

public bool WillExecute
        {
            get
            {
                return true;
            }
        }

public IMethodReturn Invoke(IMethodInvocation input,
		GetNextInterceptionBehaviorDelegate getNext)
  {
      IMethodReturn msg = null;

       //Pre method calling
       Logger.Write("Hello World + Pre Method Calling");

       msg = getNext()(input, getNext); <= Method invoked

       //Post method calling
       Logger.Write("Hello World + Post Method Calling");

       Console.ReadLine();
       return msg;
   }

We can debug and check out how the method behaves. The msg returns with an Exception of null which confirms that the Interception call is successfully completed.

Conclusion

In this example, I tried to keep things simple by concentrating on creating an application which would make extensibility work with AOP.

Download
Mahadesh_634482139436220000_MEFUnityInterception.zip
时间: 2024-10-18 21:31:32

(转)MEF+Unity的相关文章

(转)prism的MEF UNITY容器区别

http://akashkava.com/blog/391/mef-vs-unity-in-composite-application-prism/ This article describes differences between MEF and Unity which may help you in deciding which technology you must use while making composite application. Both technologies are

Miscellaneous--Tech

1. Questions: 1)EF.2)MVC/MVP/MVVM.3)page lifecyle. preInit,Init,InitCompleted,preLoad,Load,LoadCompleted,preRender,Render,RenderCompleted,Unload.4)db table index, non-index.5)union, union all.6)cache, session.7)abstract, interface.8)GC.9)http/https S

Model-View-ViewModel (MVVM) Explained 转摘自:http://www.wintellect.com/blogs/jlikness/model-view-viewmodel-mvvm-explained

The purpose of this post is to provide an introduction to the Model-View-ViewModel (MVVM) pattern. While I've participated in lots of discussions online about MVVM, it occurred to me that beginners who are learning the pattern have very little to go

Adding an instance to a MEF container

How can you add an already created instance to a MEF container/cataloge to use when resolving Imports. I want the functionality that Unity gives with the RegisterInstance method on its containers. You can use the ComposeExportedValue function for thi

MEF的学习笔记

为什么要使用MEF 在商业应用软件开发过程中,对于各个软件项目,都需要建立相应的系统框架,为了更好的规范系统的开发,提高生产效率,应该在公司级别制定相应的API标准.这些API标准将站在系统架构层次,以同样一个核心框架构建出不同的商业应用. 对于各个商业应用中存在花样繁多的需求,同时又存在一些公用的模块,为了将这些可变的和相对稳定的功能模块有机的整合在一个系统框架下,那么就需要实现系统框架的可自定义插件开发.目前在MEF之前,业界也在大量的使用如 Castle Windsor.Structure

Windows10(UWP)下的MEF

前言 最近在帮一家知名外企开发Universal Windows Platform的相关应用,开发过程中不由感慨:项目分为两种,一种叫做前人栽树后人乘凉,一种叫做前人挖坑后人遭殃.不多说了,多说又要变成月经贴了. 讲讲MEF. MEF全称Managed Extensibility Framework.我们做.Net的碰到依赖注入(DI:Dependency Injection)这一块的内容,一般会选择使用Unity或者MEF,这也是Prism主要使用的两种方式.在.Net 4.0之前,MEF一直

【Prism】MEF版HelloWorld

引言 Pirsm框架是由微软P & P小组设计的,用于构建组合式的WPF企业级应用,支持两个IOC容器,分别为Unity和MEF.官方地址为http://compositewpf.codeplex.com/,在上面可以有最新的源码和Demo,其中多数Demo都是用Unity容器构建的,而本人比较喜欢MEF,打算把Unity的Demo全部改成MEF的,先从HelloWorld开始吧. 模块HelloWorldModule 我们需要将HelloWorld.xaml先导出,,如下 [Export(&qu

[zhuan]《MEF程序设计指南》博文汇总

http://www.cnblogs.com/beniao/archive/2010/08/11/1797537.html 在MEF之前,人们已经提出了许多依赖注入框架来解决应用的扩展性问题,比如OSGI 实现以Spring 等等.在 Microsoft 的平台上,.NET Framework 自身内部包含组件模型和 System.Addin.同时存在若干种开源解决方案,包括 SharpDevelop 的 SODA 体系结构和“控制反转”容器(如 Castle Windsor.Structure

MEF——.NET中值得体验的精妙设计

MEF(Managed Extensibility Framework)是.NET Framework 4.0一个重要的库,Visual Studio 2010 Code Editor的扩展支持也是基于MEF构建的.MEF的目标是简化创建可扩展的应用程序,其核心类是ComposablePart,即具有组合能力的组件,每一个称为ComposablePart(中文可为可组合构件,不过下文一直采用英文来表示,这样比较贴切)的组件可以组合(称为Import)其它组件的功能(其它组件通过声明Export提