Search This Blog

Friday, July 22, 2011

Autofac - passing parameters to Resolve() without and with singletons

public class Person
    {
        public string name;
        public int age;

        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public Person() { }
    }

    //Autofac - passing parameters to Resolve() without and with singletons
    class Program
    {
        static void Main()
        {  
            var builder = new ContainerBuilder();
            builder.RegisterType<Person>();
            var container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var jane = container.Resolve<Person>(new NamedParameter("name", "Jane"), new NamedParameter("age", 15));
                var kate = container.Resolve<Person>(new NamedParameter("name", "Kathie"), new NamedParameter("age", 15));
                var xxx = container.Resolve<Person>();
                if (jane.Equals(kate))
                {
                    Console.WriteLine("The same");
                }
                else
                {
                    Console.WriteLine("Different");
                }
            }

            builder = new ContainerBuilder();
            builder.RegisterType<Person>().SingleInstance();
            container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var jane = container.Resolve<Person>(new NamedParameter("name", "Jane"), new NamedParameter("age", 15));
                var kate = container.Resolve<Person>(new NamedParameter("name", "Kathie"), new NamedParameter("age", 15));
                var xxx = container.Resolve<Person>();
                if (jane.Equals(kate))
                {
                    Console.WriteLine("The same");
                }
                else
                {
                    Console.WriteLine("Different");
                }
            }

            Console.WriteLine("Done! Press any key.");
            Console.ReadKey();
        }

No comments:

Post a Comment

If you like this post, please leave a comment :)