创建对象(autoFac)

首先需要在项目中安装autofac IOC框架

using Autofac;
using Xunit;

namespace createObject.Test
{
    public class createObject
    {
        //define  a interface
        interface ISpeek { }
  
        //a class to realize  interface of ISpeek
        public class Duck : ISpeek { }

        interface ICalulator
        {
            int Add(int left, int right);
        }

         
        class AddNum : ICalulator
        {
            public int Add(int left, int right)
            {
                return left + right;
            }
        }

        class Calculator
        { 
             // dependency  injection  of AddNum class
            readonly ICalulator cal;

            public Calculator(ICalulator cal)
            {
                this.cal = cal;
            }

            public int Add(int left, int right)
            {
                return cal.Add(left, right);
            }
        }

        [Fact]
        public void should_create_duck_object()
        {
            var builder = new ContainerBuilder();
            builder.Register(_ => new Duck()).As();

            IContainer build = builder.Build();
            var duck = build.Resolve();
            Assert.Equal(typeof(Duck), duck.GetType());
        }

        [Fact]
        public void should_create_calculate_object()
        {
            //tells to how to create  object
            var builder = new ContainerBuilder();
            builder.Register(_ => new AddNum()).As();
            builder.Register(c => new Calculator(c.Resolve()));
             // create build container 
            IContainer build = builder.Build();
 
            //  create Duck using Resolve 
            var calculate = build.Resolve();

            Assert.Equal(5, calculate.Add(2, 3));
        }
    }
}

你可能感兴趣的:(创建对象(autoFac))