一段代码
class Program
{
static void Main(string[] args)
{
var shop=new Shop();
shop.Add();
shop.Delete();
Console.ReadKey();
}
}
class Shop
{
readonly Log4NetServices _logServices;
public Shop()
{
_logServices = new Log4NetServices();
}
public void Add()
{
_logServices.Write("增加商品");
}
public void Delete()
{
_logServices.Write("删除商品");
}
}
问题
依赖就是依赖抽象
变形:
readonly ILogServices _logServices;
这样在实际使用中,不用管ILogServices的实现,由Shop的构造函数负责给具体实现
问题
注入就是将你需要的东西传给你,不用你自己new
变形:
class Program
{
static void Main(string[] args)
{
var shop=new Shop(new Log4NetServices());
shop.Add();
shop.Delete();
shop=new Shop(new FileLogServices());
shop.Add();
shop.Delete();
Console.ReadKey();
}
}
class Shop
{
readonly ILogServices _logServices;
public Shop(ILogServices logServices)
{
_logServices = logServices;
}
public void Add()
{
_logServices.Write("增加商品");
}
public void Delete()
{
_logServices.Write("删除商品");
}
}
问题:
dotnetcore 的ioc示例
class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILogServices, Log4NetServices>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var logServices = serviceProvider.GetService<ILogServices>();
var shop = new Shop(logServices);
shop.Add();
shop.Delete();
Console.ReadKey();
}
}
原文:https://www.cnblogs.com/sunven/p/11558861.html