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

21

Sep

POCO and Unity Application Block Part I

Posted by randypatterson  Published in 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.

view plaincopy to clipboardprint?
  1. public class MainFormPresenter
  2. {
  3. private readonly IProductRepository _productRepository;
  4. public MainFormPresenter()
  5. {
  6. //Do Something Profound
  7. }
  8. [InjectionConstructor]
  9. public MainFormPresenter(IProductRepository productRepository)
  10. {
  11. _productRepository = productRepository;
  12. }
  13. public IList<Product> GetAllProducts()
  14. {
  15. return _productRepository
  16. .Query(p => p.Name.StartsWith(“M”))
  17. .OrderBy(p => p.Name)
  18. .ThenByDescending(p => p.ListPrice)
  19. .ToList();
  20. }
  21. }
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:

view plaincopy to clipboardprint?
  1. IUnityContainer unityContainer = new UnityContainer();
  2. //Configure Container
  3. unityContainer.RegisterType<IProductRepository, ProductRepository>()
  4. //Configure constructor for MainFormPresenter
  5. unityContainer.Configure<InjectedMembers>()
  6. .ConfigureInjectionFor<MainFormPresenter>(new InjectionConstructor(typeof (IProductRepository)));
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.

view plaincopy to clipboardprint?
  1. IUnityContainer unityContainer = new UnityContainer();
  2. //Configure Container
  3. UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(“unity”);
  4. section.Containers.Default.Configure(unityContainer);
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

no comment

16

Sep

Presentation on the Unity Application Block at the Sarasota Users Group

Posted by randypatterson  Published in Events, Unity Application Block

I will be speaking about the Unity Application Block, Dependency Injection and Inversion of Control at the Sarasota .Net Users Group.

Wed, September. 17, 2008 at 6:00pm – 8:00pm.   Location: Sarasota Community Foundation, 2635 Fruitville Rd., Sarasota, FL 34237 (just west of Tuttle on the north side of Fruitville).

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 presentation will give an introduction to Dependency Injection and Inversion of Control concepts and an overview of how to use and configure the Unity Application Block to build loosely coupled applications.

Agenda:

  • Overview of Inversion on Control (IoC) Containers
    • Understanding Inversion of Control
    • Understanding Dependency Injection
  • Unity Application Block
    • Constructor Injection
    • Property (setter) Injection
  • Unity Configuration
    • Understanding Object Lifetime Management
    • Using API Configuration
      • RegisterType
      • RegisterInstance
    • Using Configuration Files
  • Managing Dependencies
  • Understanding Loosely Coupled Components
  • When is Dependency Injection Appropriate

Presentation slides and code sample

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: CodeCamp, IoC, Unity

no comment

25

Jun

I am Speaking at the Next IASA Meeting

Posted by randypatterson  Published in Events, Unity Application Block

 

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…

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

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

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

RSS

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

Tags

Azure CodeCamp IoC Podcast Presentation ReSharper TFS Unit Test Unity VS2010

Categories

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

Recent Posts

  • Support The National Day of Prayer
  • ReSharper and the Method Group Refactor
  • Moved my Blog
  • Installing VS 2010 in XP Mode
  • TFS Basic Version

Twitter

  • RT @dotnetblogs: #shanselman: A New Podcast for Developers - This Developer's Life http://ow.ly/18RfJQ-3 hours ago
  • going to go see vampires suck with my daughter. I'll have to laugh when she does because I wont understand a thing-3 days ago
  • WIndows Live Sync is the new Live Mesh http://tcrn.ch/ceh2oR-4 days ago
  • got a signed copy of @sdorman new C# book!!-1 week ago
  • RT @devfish: tampa/orlando web firestarters - http://bit.ly/9opxrF #fldev-1 week ago
  • I am constantly impressed with the quality and content of the RadioLab Science poscast http://bit.ly/Od4Ek-1 week ago
  • Reality is frequently inaccurate - Douglas Adams-1 week ago
  • Reminder: IASA Meeting tonight: @absolutdeno presenting Delivering SOA with Silverlight and WCF RIA Services http://bit.ly/aRCSuc-1 week ago

Comments

  • olegsych on Moved my Blog
  • 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

Recent Entries

  • Support The National Day of Prayer
  • ReSharper and the Method Group Refactor
  • 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
  • Random Selection of Posts

    • Visual Studio 2008 Express Released
    • Martin Fowler has a Podcast!
    • Useless Unit Test
    • ]InBetween[ Microsoft Community Summit 2008 – Free Weekend of Training
    • Top Developer Podcasts Part II
    • Tampa Bay International Association of Software Architects (IASA) Monthly Meeting
    • POCO and Unity Application Block Part I
© 2008 Randy Patterson. WordPress. Free email sender software
Theme designing by Mark Hoodia