2011-09-22 46 views
1

我知道這不是好習慣。使用NInject查找班級,但使用自己的參數構建班級

下面是一些代碼之類的演示問題(但不實際工作):

public interface IBar {} 

public interface Bar : IBar {} 

public interface IFoo {} 

public class Foo : IFoo 
{ 
    public Foo(IBar bar) 
    { 
    } 
} 

public class InjectionModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<IFoo>().To<Foo>(); 
    } 
} 

public class MyApp 
{ 
     public void DoSomething() 
     { 
      // Get a foo with a particular bar 
      var foo1 = Kernel.Get<IFoo>(new Bar()); 

      // Get another foo with a different bar 
      var foo2 = Kernel.Get<IFoo>(new Bar()); 
     } 
} 

所以我試圖做的是使用NInject到IFoo的綁定到富,但有我應用程序在運行時向構造函數提供Bar參數,而不是NInject解決IBar依賴性的通常做法。

回答

2
var foo1 = Kernel.Get<IFoo>(new ConstructorArgument("bar", new Bar()));