使用NInject查找类,但使用您自己的参数构造类

时间:2011-09-22 02:54:50

标签: 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绑定到Foo,但让我的应用程序在运行时为构造函数提供Bar参数,而不是NInject解析IBar依赖关系的常规做法。

1 个答案:

答案 0 :(得分:2)

var foo1 = Kernel.Get<IFoo>(new ConstructorArgument("bar", new Bar()));
相关问题