Register type attribute

Topics: Prism v4 - Silverlight 4, Prism v4 - WPF 4
Jun 25, 2012 at 6:38 AM
Edited Jun 25, 2012 at 6:41 AM

Hi,

I have some code that I wrote that helps registering types when using Unity.

I found it quite annoying to go and say Container.Register(...) the whole time. I ended up with having a lot of lines of code that just go and say Container.Register(...) for example:

public class ModuleA : IModule
{
	public ModuleA(IUnityContainer container)
	{
		Container = container;
	}
	
	private IUnityContainer Container { get; set; }
	
	public void Initialize()
	{
		Container.Register<Type1>();
		Container.Register<IType2, Type2>();
		Container.Register<Type3>(new ContainerControlledLifetimeManager());
		Container.Register<Type4>("Type4");
	}
}

What I wanted was the following:

public class ModuleA : IModule
{
	public ModuleA(IUnityContainer container)
	{
		Container = container;
	}
	
	private IUnityContainer Container { get; set; }
	
	public void Initialize()
	{
		Container.FindAndRegisterTypes(GetType.Module);
	}
}
The only difference will be then to have the types do the following:

[RegisteredType]
public class Type1 { }

public interface IType2 { }

[RegisteredType(From = typeof(IType2)]
public class Type2 : IType2 { }

[RegisteredType(IsContainerControlled = true)]
public class Type3 { }

[RegisteredType(Name = "Type4")]
public class Type4 { }

The code to do this will be:

public static class UnityContainerExtensions
{
	public static void FindAndRegisterTypes(this IUnityContainer container, Module module)
	{
		var types = module.GetTypes()
			.Where(x => x.GetRegisteredTypeAttribute() != null)
			.ToArray();

		foreach (var type in types)
		{
			var attribute = type.GetRegisteredTypeAttribute();
			if (attribute.IsContainerControlled)
				container.RegisterType(attribute.From, type, attribute.Name, new ContainerControlledLifetimeManager());
			else
				container.RegisterType(attribute.From, type, attribute.Name);
		}
	}

	private static RegisteredTypeAttribute GetRegisteredTypeAttribute(this Type type)
	{
		return type.GetCustomAttributes(typeof(RegisteredTypeAttribute), false).FirstOrDefault() as RegisteredTypeAttribute;
	}
}

Developer
Jun 25, 2012 at 6:36 PM

Hi Willem,

Thanks for sharing your code with the rest of the community, as it might be helpful for other users pursuing a similar scenario.

As this topic is mainly related to Unity, I believe this could be shared with the Unity community too:

As a side note, this approach seems similar to how you register a type when using MEF (with the difference that Unity is used as the container;) therefore, I believe you might find MEF interesting:

Regards,

Damian Cherubini
http://blogs.southworks.net/dcherubini

Jun 26, 2012 at 8:01 AM

Thanks DCherubini.

I've submitted a patch to Unity for this, hopefully they'll accept it.

I know about MEF and like it alot. It's just to make it easier for people already coding with Unity as the container.