加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

什么是构造函数注入(Constructor Injection)——一个具体的依

发布时间:2020-12-14 02:00:52 所属栏目:百科 来源:网络整理
导读:Disclaimer: Almost all of this was "stolen" from the Ninject Wiki 什么是构造函数注入呢,构造函数注入是不是就是一个具体的依赖注入呢,下面给个例子来解释: 构造器注入就是一个具体的依赖注入的例子: Let’s examine the idea of dependency injecti

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.

When a class is dependent on a concrete dependency,it is said to betightly coupledto that class. In this example,the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled,they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes,we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.

interfaceIWeapon 我们可以将Sword类定位一个接口

: And we can alter our Samurai class:

 weaponweapon weapon Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon,Samurai is still tightly coupled to Sword.

Fortunately,there is an easy solution. Rather than creating the Sword from within the constructor of Samurai,we can expose it as a parameter of the constructor instead.Also known as Constructor Injection.

幸运的是,有一个容易解决的方法,不是在Samurai构造函数内创建Sword,我们在将其暴露出来成为一个构造函数的参数,这就是所谓的构建函数注入:

( As Giorgio pointed out,there's also property injection(属性注入). That would be something like:

SetWeapon}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读