Resolve a new Instance

Oct 25, 2013 at 2:37 PM
Edited Oct 25, 2013 at 2:37 PM
Hi,

I registered a interface and a business class. Every time the Interface is resolved it should return a new instance of the business class. Unfortunately it is not working. The instance is always the same. D you have any ideas?

I am using FW 4.5.1 and Unity 2.1 (with Prism)
        this.container.RegisterType<ICountryBiz, CountryBiz>();

        var biz1 = this.container.Resolve<ICountryBiz>();
        biz1.Items = new ObservableCollection<Country>();
        biz1.Items.Add(new Entities.Country { Name = "Test" });

        var biz2 = this.container.Resolve<ICountryBiz>();

        bool result = ReferenceEquals(biz1, biz2);
Thank you,
Manullino
Oct 25, 2013 at 2:55 PM
I'm guessing that whatever you are seeing is related to how Prism uses Unity or how Prism gets configured.

Probably at some point CountryBiz is registered as a singleton.

The reason why I say this is that the default lifetime manager used by Unity is transient which results in a new instance being returned every time. So this code:
    public interface ICountryBiz { }

    public class CountryBiz : ICountryBiz { }

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterType<ICountryBiz, CountryBiz>();

            var biz1 = container.Resolve<ICountryBiz>();
            var biz2 = container.Resolve<ICountryBiz>();

            bool result = ReferenceEquals(biz1, biz2);
            Console.WriteLine("Result=" + result);
        }
    }

Prints out: "Result=False".

For example this code will print out "Result=True":
    IUnityContainer container = new UnityContainer();

    container.RegisterType<CountryBiz>(new ContainerControlledLifetimeManager());

    container.RegisterType<ICountryBiz, CountryBiz>();

    var biz1 = container.Resolve<ICountryBiz>();
    var biz2 = container.Resolve<ICountryBiz>();

    bool result = ReferenceEquals(biz1, biz2);
    Console.WriteLine("Result=" + result);

If you can't track down exactly where the singleton is being registered, you can explicitly override the existing LifetimeManager and set it to be transient:
    container.RegisterType<ICountryBiz, CountryBiz>(new TransientLifetimeManager());
~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to