2012-07-19 2 views
0

다음 예제는 Ninject를 사용하기 위해 다시 작성된 것처럼 보입니까?어떻게 이것을 ninject를 사용하여 다시 작성할 수 있습니까?

특히 Shuriken과 Sword 모두 사무라이를 묶는 방법은 무엇입니까?

interface IWeapon 
{ 
    void Hit(string target); 
} 

class Sword : IWeapon 
{ 
    public void Hit(string target) 
    { 
     Console.WriteLine("Chopped {0} clean in half", target); 
    } 
} 

class Shuriken : IWeapon 
{ 
    public void Hit(string target) 
    { 
     Console.WriteLine("Pierced {0}'s armor", target); 
    } 
} 

class Program 
{ 
    public static void Main() 
    { 
     var warrior1 = new Samurai(new Shuriken()); 
     var warrior2 = new Samurai(new Sword()); 
     warrior1.Attack("the evildoers"); 
     warrior2.Attack("the evildoers");  
     /* Output... 
     * Piereced the evildoers armor. 
     * Chopped the evildoers clean in half. 
     */ 
    } 
} 
+0

계속 읽기 ... https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject – scottm

+0

요점은 - 나는 예제에서 전사 용 슈리 켄과 # 2에 대한 검 – Ryan

+1

두 구현체를 모두 'IWeapon'에 바인드하고 둘 다 독립적으로 해결할 수 없으며 컨테이너를 다른 컨테이너로 선택하라는 메시지는 없습니다. 다음은 분명히 해결할 필요가있는 것을 설명 할 수있는 "극심한 세부적인"예입니다. https://github.com/ninject/ninject/wiki/Contextual-Binding – scottm

답변

2

(https://github.com/ninject/ninject/wiki/Dependency-Injection-By-Hand에서) 당신은 단순히 첫번째 Samurai를 해결 한 후 IWeapon를 리 바인드 수 :

StandardKernel kernel = new StandardKernel(); 

kernel.Bind<IWeapon>().To<Sword>().Named(); 
Samurai samurai1 = kernel.Get<Samurai>(); 
samurai1.Attack("enemy"); 

kernel.Rebind<IWeapon>().To<Shuriken>(); 
Samurai samurai2 = kernel.Get<Samurai>(); 
samurai2.Attack("enemy"); 

또는 명명 된 바인딩을 사용할 수 있습니다. 그것은 의존성에 Named 속성 추가, Samurai의 생성자 비트를 다시 정의 먼저 필요하다 : 그런 다음

public Samurai([Named("Melee")]IWeapon weapon) 
{ 
    this.weapon = weapon; 
} 

을, 당신은뿐만 아니라 당신의 바인딩에 이름을 지정해야합니다 :

StandardKernel kernel = new StandardKernel(); 

kernel.Bind<IWeapon>().To<Sword>().Named("Melee"); 
kernel.Bind<IWeapon>().To<Shuriken>().Named("Throwable"); 

Samurai samurai = kernel.Get<Samurai>(); 
samurai.Attack("enemy"); // will use Sword 

정말 많은 대안이 있습니다. @scottm이 제공하는 링크를 탐색하고 모든 내용을 확인하는 것이 좋습니다.

관련 문제