Unity Tip - Create objects in classes without UnityContainer reference

Using Setter or Constructor injection you can obtain an instance of a object and use the Activator.CreateInstance() method to instantiate new objects - the example below uses Constructor Injection:


    public interface IB
    {
        int Index { get; set; }
    }


    public class A : IA
    {
        private List<IB> bList = new List<IB>();

        public A(IB bInstance)
        {
            for (int i = 0; i < 20; i++ )
            {
                IB bitem = (IB)Activator.CreateInstance(bInstance.GetType());
                bitem.Index = i;
                bList.Add(bitem);
            }
        }
    }

Related CodePlex thread: http://www.codeplex.com/unity/Thread/View.aspx?ThreadId=31925


Tags:
Categories: Unity


Actions: E-mail | Permalink |  Grammar/Typo/Better way? Please let me know