Blog Home  Home Feed your aggregator (RSS 2.0)  
Code to Live, Live to Code - Patterns
Randy Patterson's BLog
 
 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
 Monday, March 24, 2008

Nice article posted by MSDN Magazine on Dependency Injection written by James Kovacs.  Coincides nicely with my Presentation on Unity Application Block at the Orlando Code Camp

Monday, March 24, 2008 7:16:10 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]   Patterns  |  Trackback
 Sunday, March 23, 2008

The Orlando Code Camp was a huge success.  Lots of great sessions and talented speakers. A special thanks goes out to Shawn Weisfeld of the Orlando .NET Users Group and Roy Lawson of the Lakeland Users Group, as well as the many other volunteers and speakers.

Below, I've posted my Power Point slides and code samples for both my sessions at the Code Camp.

 

The Unity Application Block

Beginning Test Driven Development

Sunday, March 23, 2008 12:29:59 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]   Events | Patterns  |  Trackback
 Wednesday, September 26, 2007

Martin Fowler coined the term "FluentInterface" to describe objects that expose an interface that flows, and is designed to be readable and concise.  The cost of this fluency is additional effort required to design the interface for your object and the slight increase in complexity.  These types of interfaces are often utilized to create configurations for your objects but can progress into an internal Domain Specific Language or DSL.

Configuration Fluent Interface Example: (sometimes called Method Chaining)

Order    
	.AddFreeShipping()    
	.IncludeItem(10)    
	.SetQuantity(2); 

 

DSL Fluent Interface Example:  (Rhino Mocks)

Expect    
	.Call(entityMock.GetID(12))    
	.IgnoreArguments()    
	.Repeat    
	.Once()    
	.Return(entityDataSet);

 

Show me the Code

Fluent interfaces are best explained by showing some code examples, so I'll take the rather prosaic Person object and create a fluent interface for it.   

Take a common Person object and write some code to instantiate and Initialize the object

       public class Person
        {
            private string _firstName;
            private string _lastName;
            private int _age;
            public bool _isActive;

            public Person(string firstName, string lastName, int age, bool isActive)
            {
                _firstName = firstName;
                _lastName = lastName;
                _age = age;
                _isActive = isActive;
            }

            public string FirstName
            {
                get { return _firstName; }
                set { _firstName = value; }
            }

            public string LastName
            {
                get { return _lastName; }
                set { _lastName = value; }
            }

            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }

            public bool IsActive
            {
                get { return _isActive; }
                set { _isActive = value; }
            }
        }
 
This is a common pattern where the constructor is used to quickly set the properties of the class.  The initialization code would look something like this.

 

Person person = new Person("Frank", "Pat", 30, true);

 

Although this code is concise it is not very readable. Is "Frank" the first name or the last name? What does the value true represent? The readability issue becomes more problematic as the number of construction parameters increase.  One solution, and the point of this post, is to write a Fluent Interface for our Person class.  The idea here is to allow each property to be set through a method call and then have that method return a reference to itself so you can continue on with next method call (often called method chaining). 

person.SetLastName("Frank").SetFirstName("Pat");
 

 

This makes our code concise and far easier to read, we now know that "Frank" is the last name.  However, an obvious issue with this pattern is that we are now cluttering up our class with methods that, when taken out of context, make little sense.  We have a FirstName property and a SetFirstName method defined on our class that obfuscates the intent. A better approach is to create an internal class that is accessed through a Set property and exposes only the Fluent Interface.

public class Person
        {
            public Person()
            {
                _set = new PersonFluentInterface(this);
            }

            private string _firstName;
            private string _LastName;
            private int _age;
            private readonly PersonFluentInterface _set;
            private bool _isActive;

            public PersonFluentInterface Set
            {
                get { return _set; }
            }

            public string FirstName
            {
                get { return _firstName; }
                set { _firstName = value; }
            }

            public string LastName
            {
                get { return _LastName; }
                set { _LastName = value; }
            }

            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }

            public bool IsActive
            {
                get { return _isActive; }
                set { _isActive = value; }
            }

            public class PersonFluentInterface
            {
                private readonly Person _person;

                public PersonFluentInterface(Person person)
                {
                    _person = person;
                }

                public PersonFluentInterface FirstName(string firstName)
                {
                    _person.FirstName = firstName;
                    return this;
                }

                public PersonFluentInterface LastName(string lastName)
                {
                    _person.LastName = lastName;
                    return this;
                }

                public PersonFluentInterface Age(int age)
                {
                    _person.Age = age;
                    return this;
                }

                public PersonFluentInterface IsActive()
                {
                    _person.IsActive = true;
                    return this;
                }

                public PersonFluentInterface IsNotActive()
                {
                    _person.IsActive = false;
                    return this;
                }
            }
        }

 

Now the code is clean, concise and quite readable.

Person person = new Person();
person.Set.FirstName("Pat").LastName("Frank").Age(30).IsActive(); 

Conclusion

This pattern for fluent interfaces is often seen in object configuration and setup.  It's fairly easy to design and the objects configuration options are readily discoverable using intellisense.  As the complexity of an objects setup increased, a fluent interface becomes a more attractive option to ease the initialization burden.

 

 

kick it on DotNetKicks.com
Wednesday, September 26, 2007 1:25:09 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [2]   C# | Patterns  |  Trackback
Copyright © 2008 Randy Patterson. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: