2017-04-23 97 views
0

我試圖重構一些代碼以使用IoC與Ninject框架。到目前爲止,我已經成功地在沒有任何構造器參數傳遞的場景中注入類。但是,在傳遞參數時遇到困難。這是下面綁定類中的第三個綁定。使用Ninject使用構造函數參數實例化一個新對象

綁定

public class Bindings : NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<ILogger>().To<Logger>(); 
      Bind<IPlayerDatadao>().To<PlayerDatadao>(); 
      Bind<IPlayerScores>().To<PlayerScores>(); 
     } 
    } 

記錄器類有一個參數的構造函數,當轉移到Ninject工作正常。

成功

// IoC creation 
    var kernel = new StandardKernel(); 
    kernel.Load(Assembly.GetExecutingAssembly()); 

    //Log User details 
    var logger = kernel.Get<ILogger>(); 
    logger.LogVisitorDetails(); 

但是,我嘗試下面拋出一個異常

失敗

 string priceString = Foo(); 
     string pointsString = Bar(); 

     return kernel.Get<IPlayerScores>(new[] { new ConstructorArgument("pointsString", pointsString), new ConstructorArgument("points", priceString) }); 

這是它的構造方法的類。

類注入

public class PlayerScores : IPlayerScores 
{ 
    [Inject] 
    public string points { get; set; } 
    [Inject] 
    public string price { get; set; } 
    public PlayerScores(string Points, string Price) 
    { 
     points = Points; 
     price = Price; 
    } 
} 

我真的不知道我應該如何處理參數,無論是在綁定類或注射

+2

'PlayerScores'似乎不是一個組件(具有行爲的類)。這是一個數據容器。這些類型的對象(DTO的查看模型,消息,實體)不應由DI容器構造。還要注意,即使'PlayerScopes'是一個組件(它的名字並不暗示),它應該[不會被注入運行時數據](https://www.cuttingedge.it/blogs/steven/pivot/entry.php ?ID = 99)。 – Steven

回答

0

點我真的不知道我該如何處理綁定分類或注入點處的參數

在綁定。你應該從你的模型中刪除任何Ninject的依賴關係:

public class PlayerScores : IPlayerScores 
{ 
    public PlayerScores(string points, string price) 
    { 
     this.Points = points; 
     this.Price = price; 
    } 

    public string Points { get; set; } 
    public string Price { get; set; } 
} 

,然後配置內核:使用

Bind<IPlayerScores>() 
    .To<PlayerScores>() 
    .WithConstructorArgument("points", "some points") 
    .WithConstructorArgument("price", "some price"); 

ToMethod這是一個比較重構友好的,因爲它避免了與參數名魔弦:

Bind<IPlayerScores>() 
    .ToMethod(ctx => new PlayerScores("some points", "some price")); 

這是說,如果2個參數是如此不穩定,他們需要對每次調用不同的值,那麼你可能不應該不要將它們作爲構造函數參數傳遞,而應作爲參數傳遞給您在運行時在類上調用的某個實例方法。

+0

我嘗試了這兩個,但他們最終將該字符串文字「一些點」傳遞給構造函數,而不是我想傳入的動態值。 – Sperick

+2

是的,這是預期的 - 我的答案的重點是構造函數參數在配置內核時應該知道 - 在綁定時間。如果情況並非如此,請在我的答案結尾處看最後一段 - 這是最後一段。 –

相關問題