Randy Patterson

Code To Live, Live To Code

  • Home
  • About

28

Sep

POCO and Unity Application Block Part II

Posted by randypatterson  Published in C#, Unity Application Block

In my previous post I covered the configuration of the Unity Application Block for Constructor Injection without modifying the class being injected.  In this post I will cover Property Injection and how write API and XML configuration.

The following code has a dependency on the ILogger class exposed through a public property in line 10 (Property Injection).

public class MainFormPresenter
{
    private readonly IProductRepository _productRepository;

    public MainFormPresenter(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public ILogger Logger { protected get; set; }

    public IList<Product> GetAllProducts()
    {
        Logger.Log("Start LINQ Query");

        return _productRepository
            .Query(p => p.Name.StartsWith("M"))
            .OrderBy(p => p.Name)
            .ThenByDescending(p => p.ListPrice)
            .ToList();
    }
}

Without the [Dependency] attribute, Unity has no idea that we need a class created and injected into the Logger Property.  Using the container API it’s a trivial matter of informing Unity of our requirements. Lines 9 and 10 in the code below will tell Unity that whenever class MainFormPresenter is created, inject Property “Logger” with a class that matches it’s type.   In addition, since the property type is ILogger, Unity needs a mapping to a concrete class or it will throw an exception (line 7).

IUnityContainer unityContainer = new UnityContainer();

//Configure Container
unityContainer
    .RegisterType<IProductRepository, ProductRepository>()
    .RegisterType<DataContext, AdventureWorksDataContext>()
    .RegisterType<ILogger, DebugLogger>();

unityContainer.Configure<InjectedMembers>()
    .ConfigureInjectionFor<MainFormPresenter>(new InjectionProperty("Logger"));

The following XML snippet will perform the same configuration

  1: <type type="UnityDemo.Views.MainFormPresenter, WindowsFormsApplication3">
  2: <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
  3: 	<property name ="Logger" propertyType="UnityDemo.Logging.ILogger, WindowsFormsApplication3"/>
  4: </typeConfig>
  5: </type>

 

Related Posts:

POCO and Unity Application Block Part I – Constructor Injection

 


















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

no comment

22

Sep

POCO and Unity Application Block Part I

Posted by randypatterson  Published in C#, Unity Application Block

Using Plain Old CLR Objects (POCO) with the Unity Application Block

Plain old CLR objects is a term borrowed from Java (POJO) that refers to objects that are not entangled with framework specific code or dependencies.  For Example, when classes have multiple constructors you can add the [InjectionConstructor] Attribute to the constructor that you want Unity to use.

public class MainFormPresenter
{
    private readonly IProductRepository _productRepository;

    public MainFormPresenter()
    {
        //Do Something Profound
    }

    [InjectionConstructor]
    public MainFormPresenter(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    public IList<Product> GetAllProducts()
    {
        return _productRepository
            .Query(p => p.Name.StartsWith("M"))
            .OrderBy(p => p.Name)
            .ThenByDescending(p => p.ListPrice)
            .ToList();
    }
}

This, however, is where POCO advocates become vocal.  The problem is by adding the attribute our class has been “polluted” with Unity specific code and it would become difficult to replace Unity with another framework.  Fortunately, Unity also allows you to accomplish the same thing using API configuration or XML configuration files.

Selecting a Constructor using the Unity API

Using the Unity API to configure which constructor to use takes just one line of code:

IUnityContainer unityContainer = new UnityContainer();

//Configure Container
unityContainer.RegisterType<IProductRepository, ProductRepository>()

//Configure constructor for MainFormPresenter
unityContainer.Configure<InjectedMembers>()
    .ConfigureInjectionFor<MainFormPresenter>(new InjectionConstructor(typeof (IProductRepository)));

Lines 7 and 8 tell unity that when the class MainFormPresenter is instantiated use the constructor that has a single parameter of type  IProductRepository. This information is difficult to find in the documentation but is straight forward and easy to read.

Selecting a Constructor using XML

Configuring Unity using an XML file is a bit more verbose but fairly easy to understand nonetheless. The first step is to tell Unity to load your config file using code similar to this.

IUnityContainer unityContainer = new UnityContainer();

//Configure Container
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(unityContainer);

Next, update your App.config, Web.config or whatever config file you choose to use to include information to inform Unity which constructor to use.

  1: <types>
  2:   <type type="UnityDemo.Views.MainFormPresenter, WindowsFormsApplication3">
  3:     <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
  4:       <constructor>
  5:         <param name ="productRepository" parameterType="AWRepository.Products.IProductRepository, AWRepository">
  6:           <dependency />
  7:         </param>
  8:       </constructor>
  9:     </typeConfig>
 10:   </type>
 11:   <type type="AWRepository.Products.IProductRepository, AWRepository"
 12:         mapTo="AWRepository.Products.ProductRepository, AWRepository"/>
 13: </types>

Lines 4-8 inform unity which constructor to use in much the same way as the API configuration preceding it.  The <dependency /> element tells unity to resolve the parameter type (IProductRepository in this case) using the mapping it already contains. 

Conclusion

Allowing configuration information, such as constructor selection, without modifying the injected class not only allows POCO but also allows us to use non-friendly dependency injection classes that we cannot modify.   For example,  Generated classes for LINQ to SQL DataContext contains 4 constructors, two with one parameter and two with two parameters. Due to the similar constructor signatures Unity will not be able to determine which one to use and will throw an exception if no guidance is provided. Fortunately we can use API or XML configuration to inform Unity how to handle these unfriendly classes.  I tend to favor the use of Attributes because they are easier to use and easier to understand intent. However, It is critical to provide indirect configuration to allow the use of classes that are not friendly to dependency Injection and to allow POCO classes when there is a need.

In my next post I will discuss how to Configure Unity for Property Injection without using the [Dependency] Attribute

 

Related Posts:

POCO and Unity Application Block Part II – Property Injection 

 

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

13

Jul

Resharper Tip #1 – Highlight Usages

Posted by randypatterson  Published in C#, ReSharper

I just love ReSharper (R#) by JetBrains, it has substantially increased my productivity while writing, and navigating code.

Quickly highlight all usages of a symbol within the current file.   To use,  place your cursor on the Type or Variable that you want to highlight then press Shift+Ctrl+F7

Highlight Usages

The Write operations are highlighted in light Red and the Read operations are highlighted in light Blue.  Pressing ESC removes the highlights. Furthermore, the R# Marker Bar to the right of your code uses to same colors to highlight all usages in the current file.  Just click on the horizontal mark to quickly navigate to the usage.

image

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: ReSharper

1 comment

2

May

Unity Application Block Event Broker

Posted by randypatterson  Published in C#, Unity Application Block

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

 

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

Nov

Visual Studio 2008 Express Released

Posted by randypatterson  Published in C#

If you don’t have an MSDN subscription and you can’t wait to try out the new Visual Studio 2008 features you can download the express edition and learn the new features while you wait for the professional edition to be available in stores.

http://www.microsoft.com/express/

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

19

Sep

The Power of the Predicate<T>

Posted by randypatterson  Published in C#

The very flexible generic collection List<T> contains several methods that take a predicate as it’s parameter.  Coupled with Anonymous Methods this provides powerfully concise code for filtering, searching and sorting your collections.

List<Person> People = new List<Person>();
People.Add(new Person("Randy", "Patterson", 40));
People.Add(new Person("John", "Smith", 15));
People.Add(new Person("Caity", "Johnson", 13));
People.Add(new Person("Jody", "Patterson", 39));
People.Add(new Person("Chloe", "Dog", 30));
People.Add(new Person("Corey", "Patterson", 18));

For Example,  to filter the collection and display only my family members requires a single line of code

IList<Person> family = People.FindAll(
    delegate(Person person)
    {
        return person.LastName == “Patterson”;
    });

And produces the following output

image

To remove the teenagers (not a bad proposition) also requires a single line

 

People.RemoveAll(
        delegate(Person person)
        {
            return person.Age > 12 && person.Age < 20; });
        }


Sorting


Sorting requires a Comparison<T> delegate instead of Predicate<T> but operates in much the same fashion.

For example, sorting by last name requires this single line of code:

People.Sort(
    delegate(Person x, Person y)
    {
        return x.LastName.CompareTo(y.LastName);
    });

a slight modification will sort the list in descending order:

People.Sort(
        delegate(Person x, Person y)
        {
            return y.LastName.CompareTo(x.LastName);
        });

To sort by Last Name then First Name would look something like this:

People.Sort(
        delegate(Person x, Person y)    
        {
            if (x.LastName == y.LastName)
                return x.FirstName.CompareTo(y.FirstName);
            else
                return x.LastName.CompareTo(y.LastName);
        });


Conclusion


I’ve just scratched the surface on what the generic List collection is capable of providing. There are several other generic methods that take delegates as parameters, such as ForEach and ConvertAll, that open up interesting possibilities in your code.   Overall I find the Anonymous Method syntax a bit kludgy but C# 3.0 promises to reduce the syntactical noise and give us true (almost) Lambda Expressions. 

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
9 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

  • Made it to Houston airport in time. Rush hour traffic is brutal-5 hours ago
  • Just wanted to mention that @olegsych (Tampa C# MVP) has finally joined Twitter!!-9 hours ago
  • RT @unclebobmartin: Nancy Pellosi: "We have to pass the bill so that you can find out what is in it."-14 hours ago
  • any of your books preloaded on it? RT @ambroselittle: RT Win a Kindle at #MIX10. Follow @Infragistics to learn how.-1 day ago
  • RT @esawdust: RT @HacknMod: 137 Years of Popular Science now Available for Free http://bit.ly/bRNNip-1 day ago
  • Running Win 7 64-bit? Fix the broken preview thumbnails for PDF files. http://bit.ly/dAVVnH-1 day 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

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

    • Installing VS 2010 in XP Mode
    • Presentation on the Unity Application Block at the Sarasota Users Group
    • Resharper Tip #1 – Highlight Usages
    • Get SnagIt and Camtasia for FREE!
    • POCO and Unity Application Block Part I
    • The Power of the Predicate<T>
    • Welcome
© 2008 Randy Patterson. WordPress. Free email sender software
Theme designing by Mark Hoodia