Randy Patterson

Code To Live, Live To Code

  • Home
  • About

30

Mar

Lazy Instantiation with Unity Application Block

Posted by randypatterson  Published in Patterns, Unit Tests, Unity Application Block

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

Bookmark It

Add to Del.icio.us Add to digg Add to DotNetKicks Add to DZone
Add to Google Bookmarks Add to reddit Add to Slashdot Add to Stumble Upon
Add to Technorati Add to Twitter Add to Yahoo My Web

Tags: IoC, Unity

1 comment

24

Mar

MSDN Article on Dependency Injection

Posted by randypatterson  Published in Patterns

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

Bookmark It

Add to Del.icio.us Add to digg Add to DotNetKicks Add to DZone
Add to Google Bookmarks Add to reddit Add to Slashdot Add to Stumble Upon
Add to Technorati Add to Twitter Add to Yahoo My Web

Tags: IoC

no comment

23

Mar

Orlando Code Camp slides and sample code

Posted by randypatterson  Published in Events, Patterns

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

Bookmark It

Add to Del.icio.us Add to digg Add to DotNetKicks Add to DZone
Add to Google Bookmarks Add to reddit Add to Slashdot Add to Stumble Upon
Add to Technorati Add to Twitter Add to Yahoo My Web
no comment

26

Sep

How to design a Fluent Interface

Posted by randypatterson  Published in C#, Patterns

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

Bookmark It

Add to Del.icio.us Add to digg Add to DotNetKicks Add to DZone
Add to Google Bookmarks Add to reddit Add to Slashdot Add to Stumble Upon
Add to Technorati Add to Twitter Add to Yahoo My Web
2 comments

RSS

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Tags

Azure CodeCamp IoC Podcast Presentation ReSharper TFS Unit Test Unity VS2010

Categories

  • C# (7)
  • Deals (2)
  • Events (11)
  • Patterns (4)
  • Podcast (5)
  • ReSharper (2)
  • TFS (1)
  • Uncategorized (6)
  • Unit Tests (1)
  • Unity Application Block (7)
  • What Burns Me (1)

Recent Posts

  • Moved my Blog
  • Installing VS 2010 in XP Mode
  • TFS Basic Version
  • Windows Azure Commercial Release this year!
  • Orlando Code Camp 2009 – Unity Presentation Slides and Code

Twitter

  • Just wanted to mention that @olegsych (Tampa C# MVP) has finally joined Twitter!!-1 hour ago
  • RT @unclebobmartin: Nancy Pellosi: "We have to pass the bill so that you can find out what is in it."-5 hours ago
  • any of your books preloaded on it? RT @ambroselittle: RT Win a Kindle at #MIX10. Follow @Infragistics to learn how.-19 hours ago
  • RT @esawdust: RT @HacknMod: 137 Years of Popular Science now Available for Free http://bit.ly/bRNNip-23 hours ago
  • Running Win 7 64-bit? Fix the broken preview thumbnails for PDF files. http://bit.ly/dAVVnH-23 hours ago
  • Don't forget to follow @OrlandoCC for the latest news on the Orlando Code Camp later this month-1 day ago
  • Lots of buzz about Amazon releasing a better browser for the #Kindle, I'd rather see better EBook oranization via Folders.-1 day ago
  • A PDF of the #OrlandoCC Agenda is out http://bit.ly/bwiZlP-1 day ago

Comments

  • Ed Holloway on TFS Basic Version
  • Jeff P on The Power of the Predicate<T>
  • Jeff Odell on Beginning ReSharper
  • Jeff Odell on POCO and Unity Application Block Part I
  • Jeff Odell on Resharper Tip #1 – Highlight Usages

Recent Entries

  • Moved my Blog
  • Installing VS 2010 in XP Mode
  • TFS Basic Version
  • Windows Azure Commercial Release this year!
  • Orlando Code Camp 2009 – Unity Presentation Slides and Code
  • Speaking at the South Florida Code Camp
  • Call for Speakers
  • Beginning ReSharper
  • POCO and Unity Application Block Part II
  • POCO and Unity Application Block Part I
  • Random Selection of Posts

    • Welcome
    • Moved my Blog
    • ]InBetween[ Microsoft Community Summit 2008 – Free Weekend of Training
    • Orlando Code Camp 2009 – Unity Presentation Slides and Code
    • Installing VS 2010 in XP Mode
    • Top Developer Podcasts Part II
    • TFS Basic Version
© 2008 Randy Patterson. WordPress. Free email sender software
Theme designing by Mark Hoodia