Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Unity and AOP Example

Unity and AOP Example


by David Hayden 


 


Let’s use AOP as a replacement of the Decorator Pattern in the previous example, Unity Application Block and Decorator Pattern. We will replace the FilteringLoggerDecorator with a custom HandlerAttribute and ICallHandler. You will need Unity v 1.2 for this example as we will be using the new Interception Extension and the InterfaceInterceptor. The example is similar to another example I wrote:



 


 


Custom ICallHandler and HandlerAttribute


One of the best things I like about both the Policy Injection Application Block and Unity v1.2 is the ability to create custom HandlerAttributes and ICallHandlers. This makes is embarassingly simple to do AOP with one of the three interceptors that ship with Unity v1.2: TransparentProxyInterceptor, InterfaceInterceptor, VirtualMethodInterceptor.


For the most part, we will take the code in the FilteringLoggerDecorator and place it in our custom ICallHandler, FilterHandler:


 



public class FilterAttribute : HandlerAttribute


{


    public override ICallHandler CreateHandler(IUnityContainer container)


    {


        return container.Resolve<FilterHandler>();


    }


}


 


public class FilterHandler : ICallHandler


{


    private readonly ILogFilter[] _filters;


 


    public FilterHandler(ILogFilter[] filters)


    {


        _filters = filters;


    }


 


    public int Order { get; set; }


 


    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)


    {


        var message = (LogMessage)input.Arguments[“message”];


        foreach (var filter in _filters)


            if (!filter.CanLog(message))


                return input.CreateMethodReturn(null);


 


        return getNext()(input, getNext);


    }


}


 


The FilterHandler will extract the message from the input parameters and run it through the filters. If the message should not be logged, the FilterHandler will not pass the request for logging through the pipeline and eventually to the default logger.


The purpose of the FilterAttribute is just to create an ICallHandler associated with the attribute. In this case, we let Unity create the FilterHandler and inject the array of ILogFilters into its constructor.


We also need to add the FilterAttribute to the Log Method on our ILogger Interface so the method is intercepted by Unity:


 



public interface ILogger


{


    [Filter]


    void Log(LogMessage message);


}


 


 


UnityContainer Registrations


Now all we need to do is register everything with Unity as such:


 



IUnityContainer container = new UnityContainer();


container.AddNewExtension<Interception>();


container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor());


 


container.RegisterInstance<ILogFilter>(“CategoryFilter”, new CategoryFilter(new[] { “Security” }));


container.RegisterInstance<ILogFilter>(“PriorityFilter”, new PriorityFilter(3, 5));


 


container.RegisterType<ILogger, ConsoleLogger>();


var logger = container.Resolve<ILogger>();


 


logger.Log(new LogMessage { Category = “Security”, Priority = 3, Message = “This is a test.” });


 


The only thing that might be new to you is the Interception Extension and InterfaceInterceptor that need to be registered and configured properly to intercept the Log Method on ILogger. You can find more information on that in the Unity Documentation and my Unity Tutorials.


 


 


Conclusion


For something so simple I would stick with the Decorator Pattern, but as the use of Decorators grow and grow in your application to achieve similar functionality you will gain the productivity and maintainability benefits of a good AOP Framework or AOP Features in various Dependency Injection and IoC Tools.


For some of the basic usages of Unity, you can watch the Unity Dependency Injection IoC Screencast.


 


Hope this helps,


Dave


 


Recent Posts:



 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>