Infragistics JQuery controls

Dependency Injection and Inversion of Control Ioc With the Microsoft Unity Container

Design for Reusability A well designed application should promote code reuse whenever possible.  Code reuse can save you time and money by allowing you to use components from previous applications to solve common problems in new projects.  The task of managing dependencies is one of the many concerns a developer faces when designing for reusability.  Dependencies are any classes that a particular class must directly instantiate and use in order to accomplish a task.  As a rule of thumb, it's good object oriented programming practice to code to an interface rather than a concrete implementation.  This will make your code flexible and built for change.   An example of a dependency You've been tasked to write a console application.  The application requires that the user authenticates before using any of the features and there is a requirement that all successfully log-ins are logged to a text file.  Here is the code for the example. TextLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class TextLogger { public void LogMessage(string message) { //Code to write the message to a text file.... Console.WriteLine(string.Format("Logging the message to a text file: {0} ", message)); } } }   AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { public AuthenticationService() { } internal void Authenticate(string userName, string password) { //Authentication logic goes here TextLogger logger = new TextLogger(); logger.LogMessage("Login was successful"); } } }   Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { class Program { static void Main(string[] args) { AuthenticationService authenticationService = new AuthenticationService(); authenticationService.Authenticate(); } } } This is a basic example for demonstration purposes only.  Now, as you can see in the AuthenticationService Authenticate method we are instantiating an instance of the TextLogger class.  So now a few weeks pass by and the customer wants you to log to a database instead of a text file.  So you create  a new class. DBLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The AuthenticationService was dependent on the TextLogger and is now dependent on the DBLogger class.  The current design requires us to change the AuthenticationService any time the customer requests a new type of logger.  The same holds true for any unit tests that we write that uses a Logger class.  As you can see the design promotes tight coupling because we are coding to a concrete implementation which is not very flexible. Introducing an interface As we can see, both logger classes have one method called LogMessage.  They share the same interface.  This is a perfect example of an instance in which we should code to an interface.  So we start by creating an interface that matches the two logging classes. ILogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public interface ILogger { void LogMessage(string message); } } Now we could simply change the logger declaration in the AuthenticationService and be done with it, however, there are still some optimizations that can be achieved.  For instance, currently the Logger declaration is a local variable inside of the Authenticate method.  Imagine were to inject the ILogger as a parameter of the AuthenticationService constructor.  This is a much more flexible design because the AuthenticationService only has knowledge of an ILogger.  Since the implementation is injected via the constructor, the class is no longer tied to any one specific implementation. Here is the updated AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { //the logger is now a class field private ILogger logger; public AuthenticationService(ILogger implementation) { //The implementation is injected via the constructor logger = implementation; } internal void Authenticate(string userName, string password) { //Authentication logic goes here logger.LogMessage("Login was successful"); } } } DBLogger.cs updated using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger : ILogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The Unity Container The Unity container allows us to use code (or a configuration file) to associate an interface with a class.  This is typically done during your application start up or the set up of your unit tests.  You register your interface and class mappings.  Then later when it's time to instantiate an instance of your objects, you ask the container to resolve an instance of the object that you need.  The Unity container will perform an internal look up and it will resolve any dependencies that your object's constructor depends on.   I prefer to register my interface/class mappings in a class that I call a module.  When my application starts I load all modules to prepare the container to resolve all of the objects that I will need.  This abstraction allows you to easily switch an interfaces implementation at run time providing a high level of flexibility to your code.  Here is a brief example of how to use the Unity container.  You will need to download the Unity assemblies from nuget or from the Microsoft patterns and practices Unity Application block site.http://unity.codeplex.com/ LoggingModule.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { public class LoggingModule { IUnityContainer _iocContainer; public LoggingModule(IUnityContainer container) { _iocContainer = container; } public void Init() { //Add any logic here to look in a config file, check a property //or any other condition to decide which implementation is registered. //register the database logger to the ILogger interface _iocContainer.RegisterType(typeof(ILogger), typeof(DBLogger)); } } } Updated Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { class Program { private static IUnityContainer _iocContainer; static void Main(string[] args) { //create our container _iocContainer = new UnityContainer(); InitializeModules(); //the container knows how to create an AuthenticationService object //as well as what type of ILogger it takes because we registered //the required class in the loggerModule. var authenticationService = _iocContainer.Resolve<AuthenticationService>(); authenticationService.Authenticate("username", "password"); Console.WriteLine("press any key"); Console.ReadKey(); } private static void InitializeModules() { //pass the container to the module //so when we register the types we can resolve them var loggingModule = new LoggingModule(_iocContainer); loggingModule.Init(); } } }   This is a very basic introduction to Unity but you I hope that you can see the possibilities when you program to interfaces and let the container take control of object creation.  You could extend this example to create a ModuleInitializer class that takes the modules that need to be initialized.   The bottom line is Program to interfaces Inject dependencies via the constructor Register your dependency interfaces to the desired class in the unity container.  You can use a module approach if you so choose. As long as your interfaces are mapped to classes in your container, the container can resolve any dependencies that your object requires when instantiated. Download the source  UnityExample.zip (723.64 kb) Happy coding! kick it on DotNetKicks.com


.NET Design Patterns : The decorator pattern. Adding new behavior to your existing objects.

  .NET Design Patterns series: Part 1 The Decorator pattern   A brief introduction to software design patterns Hello and welcome to my first article in a series on design patterns.  A design pattern is simply a documented solution to a common software design problem.  This idea is extremely useful in the world of software development.  When designing and writing code, chances are whatever your task may be, someone has already accomplished what you've been tasked to do.  In fact, many developers have probably accomplished the task at hand.  Why reinvent the wheel?  There are many benefits to practicing and using design patterns. Industry standards Design patterns are deeply ingrained in the world of software development.  As such, you can look at tried and tested design patterns as "best practices".  If you practice and understand solutions that are accepted by the software development community, your software solutions will improve as a result. Efficient Communication Design patterns are defined and described using a unified set of terms.  As you practice design patterns, you will master these terms and in effect, you will be able to communicate much more effiecently with other developers.  You will spend less time trying to describe a potential design when you understand how to describe the concepts clearly by using a unified terminology.  As a result, other junior developers on your team will be more likely to try to learn design patterns which will make your overall team more efficient. Brief history of design patterns Kent Beck and Ward Cunningham began experimentation with design patterns in the context of computer science in the year 1987.  Most of the works on design patterns have been based on their works. Popular books on design patterns Design Patterns: Elements of Reusable Object-Oriented Software Patterns of Enterprise Application Architecture. Pattern-Oriented Software Architecture, Volume 1: A System of Patterns Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects Pattern #1: The Decorator pattern, Adding new behavior to existing objects I've decided to start this series with patterned called the Decorator pattern.  I suppose it's best to start with the formal definition of the pattern. The Decorator Pattern attaches additional responsibilities to an object dynamically.  Decorators provide a flexible alternative to subclass for extending functionality. Too much inheritance can be a bad thing  Inheritance is an important part of object oriented design.  However, just like anything else, too much subclassing can be a bad thing.  The idea behind a great object oriented application is to design your objects with change and reuse in mind.  If you find yourself creating 20+ subclasses of an abstract class, you may want to step back and look at your design.  With each new subclass that you design, there's a another class that you must maintain and change.  Remember, to always design your classes to be Open for extension, closed for modification.  This makes for easier maintienence and flexible designs. The Decorator pattern allows you to add behavior to existing classes at run time through object composition.  This means we create a class to "decorate" another class with new functionality.  The class to be decorated would be passed into the decorator object's constructor and the reference would be stored as a field.  This process can be repeated to achieve new functionality when calling the common contract of the class to be decorated. The article example Imagine the idea of an article.  There are many different types of articles.  There are news paper articles, blog articles, code project articles, magazine articles.  The list goes on and on.  In the age of electronic articles, it would be handy to write an article class and provide a post method.  The post method would contain any external site API calls required to publish the article to it's destination.  When posting an article, you may want to accomplish other tasks at the same time, such as advertise the article.  Perhaps you'd like to advertise your new article via Twitter.   OOP Principals: Open for extension and closed for modification You could add the code to tweet your new article right into your the article base class, however, this would go against our Object Oriented design princiapl "Open for extension, closed for modification".  Wouldn't it be better to add this new behavior to our articles at run time?  The decorator pattern allows us to do just that!   Examine the following class diagram.  And here is the code.. Article.cs   using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// Defines the methods and properties required for an article to be posted on the web. /// </summary> public abstract class Article { #region "properties" public string Title { get; set; } public string Url { get; set; } public string Body { get; set; } public string Author { get; set; } #endregion #region "methods" /// <summary> /// Provides a method to "Post" the article to it's destination. /// </summary> public abstract void Post(); #endregion } } Decorator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// This interface takes an /// </summary> public abstract class Decorator : Article { //Holds a reference to the componoent to be decorated //in this case an article. protected Article _article; /// <summary> /// A emthod to provide the article to be extended. /// </summary> /// <param name="article">The article in which to add new behavior</param> public void SetArticle(Article article) { _article = article; } /// <summary> /// Implementation of the base classes' post method which calls the /// referenced article's post method as well. /// </summary> public override void Post() { if (_article != null) { _article.Post(); } } } } CodeProjectArticle.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// Represents an article to be posed to codeproject.com /// </summary> public class CodeProjectArticle : Article { public CodeProjectArticle() { } /// <summary> /// This would normally contain any calls to post the article to the codeproject.com automatically /// </summary> public override void Post() { Console.WriteLine("Posting the article {0} to {1}", this.Title, this.Url); Console.WriteLine(); } } } Tweetable.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { /// <summary> /// This interface takes an /// </summary> public class Tweetable : Decorator { //Holds a reference to the componoent to be decorated //in this case an article. protected Article _article; public Tweetable(){ } /// <summary> /// A emthod to provide the article to be extended. /// </summary> /// <param name="article">The article in which to add new behavior</param> public Tweetable(Article article) { _article = article; } /// <summary> /// Implementation of the base classes' post method which calls the /// referenced article's post method as well. /// </summary> public override void Post() { base.Post(); if (_article != null) { _article.Post(); } TweetArticle(); } public void TweetArticle() { if (_article != null) { Console.WriteLine("Tweeting about your recent article posting entitled {0}", _article.Title); Console.WriteLine(); } } } } BlogPost.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { public class BlogPost : Tweetable { protected Article _article; public BlogPost() { } public BlogPost(Article article) { _article = article; } public override void Post() { base.Post(); Console.WriteLine("Posting a personal blog called {0} to my personal blog site {1}.", this.Title, this.Url); Console.WriteLine(); } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPatternApplication { public class Program { public static void Main(string[] args) { //Create an instance of our code project article CodeProjectArticle codeProjectArticle = new CodeProjectArticle { Title = "Code Project Article: Why learn Assembly language?", Author = "Buddy James", Body = "All of the article's body would go here.", Url = "http://www.codeproject.com/Articles/89460/Why-Learn-Assembly-Language" }; codeProjectArticle.Post(); BlogPost personalBlogPost = new BlogPost { Title = "The Decorator pattern. How to extend the behavior of your existing objects", Author = "Buddy James", Body = "All of the article's contents would go here.", Url = "http://www.refactorthis.net" }; //Lets post a tweet when we post our blog article Tweetable TweetBlogPost = new Tweetable(personalBlogPost); TweetBlogPost.Post(); Console.ReadLine(); } } } I've attached the entire solution so that you can see how it works.  You can download the solution Here DecoratorPatternApplication.zip (78.94 kb)   Notice that the post and tweet methods contain calls to Console.WriteLine().  Obviously in a real scenario these methods would contain calls to actually "post" or "publish" the  article. I hope you've enjoyed my first of many articles on design patterns. Thanks and keep reading! ~/Buddy James kick it on DotNetKicks.com  


About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List