A piece of code
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("Increase commodity"); } public void Delete() { _logServices.Write("Delete merchandise"); } }
problem
- Depending on specific Log4Net Services, FileLog Services need to be changed
rely on
Dependence is dependent on abstraction
Deformation:
readonly ILogServices _logServices;
So in practice, regardless of the implementation of ILog Services, Shop's constructor is responsible for the specific implementation.
problem
- Shop itself does not know whether to use Log4Net Services or FileLogServices, but users certainly do.
injection
To inject is to pass on what you need, without your own new
Deformation:
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("Increase commodity"); } public void Delete() { _logServices.Write("Delete merchandise"); } }
Question:
- There are so many people in need. I'm new one by one.
- There are many kinds of needs. I'm new one by one.
- Can you put new things together and get them from the people you need?
IOC
ioc example of dotnetcore
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(); } }