I am not sure if this is a unity bug but can anyone help me explain why the below program in the third case prints 150?
void Main()
{
// Test 1
Derived d = new Derived();
d.Height.Dump(); //Prints 10
// Test 2
IUnityContainer unityContainer = new UnityContainer();
unityContainer.Resolve(typeof(Derived)).Dump(); // Prints 10
// Test 3
unityContainer.RegisterType<IPrintHeightService<Derived>, PrintHeightService<Derived>>();
var output = unityContainer.Resolve<IPrintHeightService<Derived>>();
output.Show(); //Prints 150
}
public interface IHasHeight
{
Int32 Height {get; set;}
}
// Define other methods and classes here
public class Default : IHasHeight
{
public Int32 Height {get; set;}
public Default()
{
Height = 150;
}
}
public class Derived : Default
{
public new Int32 Height {get { return 10;}}
}
public interface IPrintHeightService<T> where T:IHasHeight, new()
{
void Show();
}
public class PrintHeightService<T> : IPrintHeightService<T> where T:IHasHeight, new()
{
private IHasHeight objectWithHeight;
public PrintHeightService(IUnityContainer unityContainer)
{
objectWithHeight = (T) unityContainer.Resolve(typeof(T));
}
public void Show()
{
Console.WriteLine(objectWithHeight.Height); // Prints 150
}
}
I suspect this is because of the intializers are run from derived to base as explained (http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx) but why it is obvious with unity and not otherwise?
Thanks much.
It’s because you declared Height as
new. By declaring it asnew, Derived doesn’t override Height, it just hides it. That has nothing to do with the initializers.Which means that the new implementation doesn’t have anything to do with the virtual Property declared by the Interface, it just happens to have the same name, thus “hiding” it. By calling Height over
IHasHeight(in theShow()method ofPrintHeightServiceyou access a field with that type), the property declared by the interface is called, which is implemented inDefault. You will only getDerived.Height, if you call it via a reference of the typeDerived.You can see for yourself: Change the type of the variable
din example 1 toDefaultorIHasHeightand you’ll see that you will get 150, too.If you truly want to override the implementation of
HeightinDerivedHeightasvirtualinDefaultand thenHeightasoverrideinDerivednewmodifier.