2009-09-28 9 views
15

Jestem nowy w kontenerach IOC i uczę się Ninject. Używam wersji 2.0, świeżo pobranej z Github.Parametr konstruktora Ninject 2.0 - jak ustawić, gdy obecny jest domyślny konstruktor?

Próbuję ustawić parametr ciąg na konstruktorze, gdy obecny jest również domyślny konstruktor. Przechodzę przez źródło Ninject, ale nie jestem dostatecznie zaznajomiony z wzorcami używanymi do łatwego wskazania tego, czego mi brakuje.

Oto moja próba aplikacja konsoli. „Hello World!”.

 static void Main(string[] args) 
     { 
     IKernel kernel = new StandardKernel(); 
     kernel.Bind<ITestClass>().To<TestClass>() 
      .WithConstructorArgument("message", "Hello World!"); 

     var testClass = kernel.Get<ITestClass>(); 

     // Does not work either: 
     //var testClass = kernel.Get<ITestClass>(new ConstructorArgument("message", "Hello World!")); 

     testClass.DisplayMessage(); 
     Console.ReadLine(); 
     } 
    } 

public interface ITestClass 
    { 
    void DisplayMessage(); 
    } 

public class TestClass : ITestClass 
    { 
    public TestClass() 
     { 
     this.message = "Wrong message :("; 
     } 

    private string message; 
    public TestClass(string message) 
     { 
     this.message = message; 
     } 

    public void DisplayMessage() 
     { 
     Console.WriteLine(this.message); 
     } 

kodu drukuje „Zła wiadomość :(” do konsoli Jeśli usunąć domyślnego konstruktora w TestClass uzyskać Czym jestem brakuje tu

aby wyjaśnić:?. Chcę klasę do print „Hello World!” do konsoli z teraźniejszością domyślnego konstruktora

Odpowiedz

8

ciąg nie jest self-Bindable, więc to nie jest liczony jako zależność Gdy uruchomiony jest executor .ctor, otrzyma on domyślny plik .ctor i ciąg znaków .ctor to samo, ponieważ zależności nie można rozwiązać. Możesz to naprawić, przypisując ciąg znaków .ctor

[Inject] 
public TestClass(string message){...} 

i twój kod będzie działał poprawnie.

+0

Wielkie dzięki Ian! – Stuart

+0

Właśnie popełniłem wcześniejszy patch, który powinien również zadbać o ten problem bez atrybutu [Inject]. Parametry są teraz punktowane podczas oceniania, który .którym użyć. –

Powiązane problemy