Blog Home  Home Feed your aggregator (RSS 2.0)  
Code to Live, Live to Code - Unity Application Block
Randy Patterson's BLog
 
 Wednesday, June 25, 2008

 

Dependency Injection using the Microsoft Unity Application Block

The Microsoft Unity Application Block is a lightweight Dependency Injection Container that is currently being incorporated into the latest releases of Enterprise Library and the Composite Application Library (Prism). This session will give an introduction to Dependency Injection and Inversion of Control concepts and a brief overview of how to use the Unity Application Block to build loosely coupled applications.

My goal is to finish by leading a discussion on the pros and cons of Dependency Injection, Loosely coupled and Tightly coupled components. When we leave I hope everyone will have a deeper understanding of these principles and how and when to apply them.

When & Where:
Thursday, June 26, 2008 from 06:30 PM - 08:30 PM (ET)
Microsoft Corporation
3000 Bayport Drive
Suite 480
Tampa, FL 33607
View a map
View 1-Click Directions

Please be aware that the outside doors lock and the elevators need a security key after 7:00 PM.

 

Please Register for the event:

Update:

Here are my slides from the presentation:

 

For additional information I recommend the following 2 part PodCast on Dependency Injection:

podcast Dependency Injection and Inversion of Control

 

podcast More Dependency Injection and Inversion of Control

 

Finally, the following book is highly recommended:

Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series)
by Robert C. Martin, Micah Martin

Read more about this book...
Wednesday, June 25, 2008 9:30:20 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]   Events | Unity Application Block  |  Trackback
 Friday, May 02, 2008

The Unity Application Block IoC Container comes with a little know extension for creating loosely coupled events called the Simple Event Broker.  The Unity Event Broker supports multiple publishers and multiple subscribers to the same event name.  The decoupled model prevents subscribers from knowing about publishers and publishers from knowing about subscribers.

 

image

 

The Event Broker source code can be found under the Unity Quick Starts normally located here

"C:\Program Files\Microsoft Unity Application Block 1.0\UnityQuickStarts.zip\UnityQuickStarts\CS\EventBroker.sln". 

In order to use the Extension make sure you have your project reference the EventBrokerExtension.dll and the SimpleEventBroker.dll.

Next, you need to configure Unity by adding the Event Broker Extension to the Container.

        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            UnityContainer rootContainer = new UnityContainer();

            rootContainer.AddNewExtension<SimpleEventBrokerExtension>();
            
            Application.Run(rootContainer.Resolve<DefaultForm>());
        }

 

This gives you two new Attributes recognized by Unity, [Publishes(eventName)] and [SubscribesTo(eventName)] where eventName is a string that uniquely identifies the loosely coupled event.

The attribute [Publishes] is applied to an event and lets the event broker know that when this event is raised, any methods that are subscribed to eventName are called. 

For Example:

        [Publishes("event://Transaction/Complete")]
        public event EventHandler TransactionComplete;

Best Practice:


It is recommended that you not hard code the Event Name parameter.  Instead use a class that contains the event names as public string constants.

[SubscribesTo(EventTopicNames.TransactionComplete)]

This prevents typos in the event name string and also allows a Usages Search in Visual Studio to quickly locate all Publishers and all Subscribers of an event.

 

The event broker will create a loosely coupled event named "event://Transaction/Completed" [1] and link the .NET event TransactionComplete [2] to it. The following subscriber code

        [SubscribesTo("event://Transaction/Complete")]
        public void TransactionCompleteHandler(object sender, EventArgs e)
        {
            //Do Something.....
        }

informs the Event Broker that method TransactionCompleteHandler [3] needs to be called whenever the loosely coupled event named "event://Transaction/Completed" is published. Notice that neither the publisher nor the subscriber is aware of the other.

Conclusion

The ability for your application to communicate between controls without resorting to directly linking one class to another increases the reusability of your code.  The Unity Event Broker is, as it's name implies, a rather simple implementation of loosely coupled events but it is a good start none the less.  for example,  I would like to see a way for subscribers to indicate that methods should be called on a background thread instead of always on the Publisher's thread. In future posts I will show how to register events for publication when you cannot add the [Publishes] attribute directly to an event declaration (useful for Button and Menu Click events or third part controls)

 

  1. I use the URL style string to name the decoupled events purely out of habit.  Obviously, any string will do but I find the URL format to be clean and easy to read.
  2. Events must be scoped public in order for the Event Broker to detect the Publishes attribute
  3. The subscription method must be scoped public in order for the Event Broker to detect the SubscribesTo attribute

 

Friday, May 02, 2008 1:02:08 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]   C# | Unity Application Block  |  Trackback
 Saturday, March 29, 2008

Configuring the Unity Application Block for just-in-time Instantiation. 

Out of the box, Unity does not provide a way to configure your dependencies so that they are resolved only if needed.  Lazy Instantiation would be desirable if your dependency is and required only under certain circumstances or you would like to delay object creation of a resource intensive dependency until needed.

For Lazy Instantiation, the first obstacle to overcome when using IoC Containers like Unity, is to have your components get a reference to the container so the dependency creation can be delegated to it when the need arises.  My first inclination was to wrap Unity in a Singleton and have the component reference this in order to resolve the dependency. 

Container.Instance.Resolve<IProductService>();

Singleton's are, however, notoriously difficult to test and very rigid in design.  Used in this manner,  a Singleton is nothing more than a global variable wrapped in a buzzword.  so I wanted a different approach.  Since we are using a Dependency Injection Framework, why not have the container inject a reference to itself into our components.

1.  First, configure the Unity container so that it can return a reference to itself.

image

2.  Next, create a property on your class to get a reference to the Unity container that created it.

image

3.  Finally, have the container resolve the dependency the first time it's referenced. 

image

Unit Testing

Testing is straight forward as well.   You could have your unit test use reflection to reach in and set the private field (_productService) to your mock object.  However,  giving your Unit Tests access to private members violates the "Use the Front Door First" Test Automation Principle and should be avoided if possible.  Alternatively, you could create a mock object for IUnityContainer and have it return a mock object for IProductService when the Resolve method is called.

Using RhinoMocks, the Unit Test would look something like this:

 

image

 

 kick it on DotNetKicks.com

Saturday, March 29, 2008 8:48:37 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [1]   Patterns | Unit Tests | Unity Application Block  |  Trackback
Copyright © 2008 Randy Patterson. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: