首先需要在项目中安装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<ISpeek>();
IContainer build = builder.Build();
var duck = build.Resolve<ISpeek>();
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<ICalulator>();
builder.Register(c => new Calculator(c.Resolve<ICalulator>()));
// create build container
IContainer build = builder.Build();
// create Duck using Resolve
var calculate = build.Resolve<Calculator>();
Assert.Equal(5, calculate.Add(2, 3));
}
}
}