Unity’s documentation says of the RegisterInstance<> method that registers an instance so that that particular instance is returned everytime Resolve<> is called.
However, this example below shows that each time Resolve<> is called, a new instance of the type is returned.
Why is this?
using System; using System.Windows; using Microsoft.Practices.Unity; namespace TestUnity34 { public partial class Window1 : Window { public Window1() { InitializeComponent(); Validator validator1 = new Validator(); IUnityContainer container = new UnityContainer(); container.RegisterInstance<IValidator>(validator1); Validator validatorCopied = validator1; Console.WriteLine(validator1.GetHashCode()); //14421545 Console.WriteLine(validatorCopied.GetHashCode()); //14421545 Validator validator2 = container.Resolve<Validator>(); Console.WriteLine(validator2.GetHashCode()); //35567111 Validator validator3 = container.Resolve<Validator>(); Console.WriteLine(validator3.GetHashCode()); //65066874 } } interface IValidator { void Validate(); string GetStatus(); } public class Validator : IValidator { public void Validate() { } public string GetStatus() { return 'test'; } } }
You have configured your container with IValidator so you will have to resolve using IValidator instead of Validator:
Alternatively you can keep your registration using Validator but then you have to resolve using Validator as well: