在介绍依赖注入(Dependency Injection)之前先介绍下松,紧耦合的概念。 提到松紧耦合就不得不提接口(Interface),我们直接上demo.
先来看下紧耦合的例子:
class Program { static void Main(string[] args) { var engine = new Engine(); var car = new Car(engine); car.Run(3); Console.WriteLine(car.Speed); } } public class Engine { public int RPM { get; private set; } public void work(int gas) { this.RPM = 1000 * gas; } } class Car { private Engine _engine; public Car(Engine engine) { this._engine = engine; } public int Speed { get; private set; } public void Run(int gas) { _engine.work(gas); this.Speed = _engine.RPM / 100; } }
一旦Engine中work发生改变,依赖它的Car也需要更改。项目小还容易修改,要是项目复杂,就很难定位了。
我们再来看下松耦合的例子,提到松耦合,一般都会借助接口来达到所要的效果,接口定义了一组契约,继承调用它的类都会受到这组锲约的约束,调用者不用关心这组功能会由谁提供(实现):
interface IPhone { void Dail(); void PickUp(); void Send(); void Receive(); } class ApplePhone:IPhone { public void Dail() { Console.WriteLine("Buy?"); } public void PickUp() { Console.WriteLine("Buy??"); } public void Send() { Console.WriteLine("Buy???"); } public void Receive() { Console.WriteLine("Buy????"); } } class XiaoMiPhone:IPhone { public void Dail() { Console.WriteLine("Are U Ok?"); } public void PickUp() { Console.WriteLine("Hello?"); } public void Send() { Console.WriteLine("Think You!"); } public void Receive() { Console.WriteLine("Think You Very Much!"); } } class User { private IPhone _phone; public User(IPhone phone) { this._phone = phone; } public void UsePhone() { _phone.Dail(); _phone.Dail(); _phone.Dail(); } } static void Main(string[] args) { var user = new User(new ApplePhone()); var user2 = new User(new XiaoMiPhone()); user.UsePhone(); user2.UsePhone(); }
通过继承手机的统一接口规范我们可以编写多个手机型号,这样用户就可以轻松实现换手机了,这个就是利用接口来实现松耦合。
接着我们一起来看下依赖注入,依赖注入分为以下三种类型:
结构注入(Structure Injection):
属性注入(Property Injection):
方法注入(Method Injection):
原文:https://www.cnblogs.com/jessicaxia/p/13638487.html