Replace factory class/method with unity

Nov 28, 2010 at 9:16 AM

Hello,


i try to refactor my code and want use unity. I want replace a factory method by unity functionality. I have the following code:

public interface IColor
{
Show();
}

public class RedColor : IColor
{
public void Show(){}
}

public class GreenColor : IColor
{
public void Show(){}
}

public class Person
{
public Color FavoriteColor {getset;}
}

public enum Color
{
Red,
Green
}

public static class ColorFactory
{
public static IColor Create(Person p)
{
switch(p.FavoriteColor)
{
case Color.Red:
return new RedColor();
case Color.Green:
return new GreenColor();
default:
}
}
}


The class ColorFactory / method IColor Create(Person p) shall be replaced with some magic unity code.
In future it can be, that i have additional value in enum Color (Blue) , new implementation of IColor (public class BlueColor : IColor{..})
I dont want change the factory method ( case in switch ). Can i solve/replace it with Unity.


Thanks a lot


Chris

Nov 29, 2010 at 12:51 AM
Edited Nov 29, 2010 at 1:09 AM

Hi Chris,

I would use a named registration mapped to the Enum values

 

container.RegisterType<IColor, RedColor>( Color.Red.ToString() );
container.RegisterType<IColor, GreenColor>( Color.Green.ToString() );
container.RegisterType<IColor, BlueColor>( Color.Blue.ToString() );

IColor color = container.Resolve<IColor>( p.FavoriteColor.ToString());

 

public static class ColorFactory
{
	public static IColor Create(Person p)
	{
		if ( container.IsRegistered<IColor>( p.FavoriteColor.ToString() )
			return container.Resolve<IColor>( p.FavoriteColor.ToString() );

		return container.Resolve<IColor>( #Insert Default Color# );
	}
}

If you use the IsRegistered method, you will never have to change the static factory method again, even when you add new color implementation.
If you haven't registered a particular color, then you will get the default.  No more switch statement.

You could even automate all the container registrations by annotating all IColor implementation with an Attribute ( a lot of appropriate attributes in the System.ComponentModel namespace ), 
or use a naming convention, and discovering by reflection.

Dec 1, 2010 at 9:48 AM

Hi rslaney,

 

thanks for your answer - it sounds interesting! I will try to follow this approach.

 

greatings

 

chris