2013-11-02 43 views
1

我們使用Ninject進行依賴注入。我們使用自由格式解釋的DDD設計我們的代碼,其中域對象是IThing。通用類型Ninject自動解析

在下面的代碼中,如何使用IThing實例獲取IThingControl?

interface IThing {} 
class Thing : IThing {} 

interface IThingControl<T> where T:IThing {} 
class ThingControl<Thing> {} 

class Module : NinjectModule { 
    public override void Load() { 
     Bind<IThingControl<Thing>>().To<ThingControl>(); 
    } 
} 

class SomewhereInCode { 
    void AddControls() { 
     List<IThing> things = new List<IThing> { 
      new Thing() 
     }; 
     foreach (IThing thing in things) { 
      IThingControl<IThing> control = _kernel.Get(); // <----- eh? 
      this.Controls.Add(control); 
     } 
    } 
} 

回答

2

你可以使用MakeGenericTypehere)的實例,但你不能將它轉換爲IThingControl<IThing>

interface IThing { } 
class Thing1 : IThing { } 
class Thing2 : IThing { } 
interface IThingControl<T> where T : IThing { } 
class ThingControl<Thing> { } 

class Module : NinjectModule { 
    public override void Load() 
    { 
     Bind(typeof(IThingControl<>)).To(typeof(ThingControl<>)); 
    } 
} 

[TestFixture] 
public class SomewhereInCode 
{ 
    [Test] 
    public void AddControls() 
    { 
     IKernel kernel = new StandardKernel(new Module()); 
     List<IThing> things = new List<IThing> { new Thing1(), new Thing2() }; 
     Type baseType = typeof(IThingControl<>); 

     foreach (IThing thing in things) 
     { 
      Type type = baseType.MakeGenericType(thing.GetType()); 
      dynamic control = kernel.Get(type); 
      Assert.That(
       control is IThingControl<IThing>, 
       Is.False); 
     } 
    } 
}