什么是构造函数注入(Constructor Injection)——一个具体的依
Disclaimer: Almost all of this was "stolen" fromthe Ninject Wiki 什么是构造函数注入呢,构造函数注入是不是就是一个具体的依赖注入呢,下面给个例子来解释: 构造器注入就是一个具体的依赖注入的例子:
Let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game,where noble warriors do battle for great glory. First,we’ll need a weapon suitable for arming our warriors. class Sword { publicvoidHit(string target)Console.WriteLine("Chopped {0} clean in half",);}} Then,let’s create a class to represent our warriors themselves. In order to attack its foes,the warrior will need an Attack() method. When this method is called,it should use its Sword to strike its opponent. Samuraireadonly sword;Samurai()this.sword =newSword();Attacksword(target Now,we can create our Samurai and do battle!ProgramstaticMainvar warrior warrior"the evildoers" As you might imagine,this will printChopped the evildoers clean in halfto the console. This works just fine,but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor,we have to modify the implementation of the class in order to make this change. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |