Project Description
This project is unity container extension that is attribute base register.

Feature
  • Annotation type to register the UnityContainer.
    • FromType, ToType, Name and LifetimeManager.
  • Can register more than one type.
    • UnityExportAttribute allow multiple.

Example
Create types.
using System;
using Codeplex.Unity.AutoRegister;
using Microsoft.Practices.Unity;

// annotation base regist
[UnityExport]
public class GreeterClient
{
    [Dependency]
    public IGreeter Greeter { get; set; }

    public void Execute()
    {
        Console.WriteLine(this.Greeter.Greet());
    }
}

public interface IGreeter
{
    string Greet();
}

// multi regist
[UnityExport(FromType = typeof(IGreeter))]
// set LifetimeManager
[UnityExport(Name = "Singleton", 
    FromType = typeof(IGreeter), 
    LifetimeManager = typeof(ContainerControlledLifetimeManager))]
public class Greeter : IGreeter
{
    public string Greet()
    {
        return "Hello world";
    }
}


How to regist container.
var container = new UnityContainer();
// add extension
container.AddNewExtension<AutoRegistExtension>();
// configure extension
var config = container.Configure<AutoRegistExtension>();
// add assembly
config.AddProvider(
    new AssemblyRegistTypeTraitProvider(typeof(GreeterClient).Assembly));


You can resolve type in container.
// annotation base regist and injection
var client = container.Resolve<GreeterClient>();
client.Execute(); // -> Hello world

// annotation base LifetimeManager
var singleton1 = container.Resolve<IGreeter>("Singleton");
var singleton2 = container.Resolve<IGreeter>("Singleton");
Console.WriteLine("singleton1 == singleton2 -> {0}", object.ReferenceEquals(singleton1, singleton2)); // singleton1 == singleton2 -> true


Custom export attribute
using System;
using Codeplex.Unity.AutoRegister;
using Microsoft.Practices.Unity;

// custom export
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class CustomExportAttribute : UnityExportAttribute
{
    public CustomExportAttribute()
    {
        // custom property injection
        this.InjectionMembers = new[]
        {
            // injection ViewModel instance.
            new InjectionProperty("DataContext", new ResolvedParameter<ViewModel>())
        };
    }
}

// custom export
[CustomExport]
public class Control
{
    // !!no set Dependency annotation!!
    public object DataContext { get; set; }
}
[UnityExport]
public class ViewModel
{
}

Auto inject ViewModel!!
// custom injection
var control = container.Resolve<Control>();
Console.WriteLine("control.ViewModel = {0}", control.DataContext); // -> control.ViewModel = SampleApplication.Library.ViewModel

Last edited Mar 27, 2012 at 2:23 PM by okazuki, version 2