Search This Blog

Friday, July 22, 2011

Autofac - reading other container's Metadata

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

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

        public Person() { }
    }

    public class Other
    {
        readonly IEnumerable<Meta<Person>> _personsMeta;

        public Other(IEnumerable<Meta<Person>> personsMeta)
        {
            _personsMeta = personsMeta;
        }

        public void Write()
        {
            IEnumerable appender = _personsMeta;
            IEnumerator enumer = appender.GetEnumerator();
           
            enumer.MoveNext();
            Meta<Person> person = (Meta<Person>)enumer.Current;
            Dictionary<string,object> metaDict = (Dictionary<string,object>)person.Metadata;

            var info = metaDict.First(a => a.Key.Equals("descr")).Value;
            var info2 = metaDict.Where(a => a.Key.Equals("descr")).Select(a => a.Value).First();
            var info3 = (from entry in metaDict where entry.Key == "descr" select entry.Value).First();

            Console.WriteLine("Person container metadata: \n\"" + info3 + "\"");
        }
    }

    //Autofac - reading other container's Metadata
    class Program
    {
        static void Main()
        {  
            var builder = new ContainerBuilder();
            builder.RegisterType<Person>().WithMetadata("descr", "Describes basic properties of the client, like name or age");
            builder.Register<Other>(c => new Other(c.Resolve<IEnumerable<Meta<Person>>>() ));

            var container = builder.Build();
            using (var lifetime = container.BeginLifetimeScope())
            {
                var otherObj = container.Resolve<Other>();
                otherObj.Write();
            }

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

No comments:

Post a Comment

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