Blog Home  Home Feed your aggregator (RSS 2.0)  
Code to Live, Live to Code - POCO and Unity Application Block Part II
Randy Patterson's Blog
 
 Sunday, September 28, 2008

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

 

Sunday, September 28, 2008 10:00:01 AM (Eastern Daylight Time, UTC-04:00)  #      C# | Unity Application Block  |  Trackback
Copyright © 2009 Randy Patterson. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.