C# 如何正确使用Ninject';s名为示波器分机?

C# 如何正确使用Ninject';s名为示波器分机?,c#,.net,ninject,ninject-extensions,C#,.net,Ninject,Ninject Extensions,我有一个模式,在我工作的时候总是出现。我几乎完全是一名web开发人员,Ninject的InRequestScope可以满足我99%的需求 以下是模式: // abstractions interface IFoo { void FooMe(); int GetSomeValue(); } interface IBar { void BarMe(); } interface IFooBar { void FooAndBar(); } // concrete

我有一个模式,在我工作的时候总是出现。我几乎完全是一名web开发人员,Ninject的InRequestScope可以满足我99%的需求

以下是模式:

// abstractions

interface IFoo {
    void FooMe();
    int GetSomeValue();
}

interface IBar {
    void BarMe();
}

interface IFooBar {
    void FooAndBar();
}

// concrete classes

class Foo : IFoo {
    public void FooMe() { Console.WriteLine("I have fooed"); }
    public void GetSomeValue() { return 123; }
}

class Bar : IBar {
    private readonly IFoo _Foo;

    public Bar(IFoo foo) { _Foo = foo; }

    public void BarMe() { Console.WriteLine("Bar: {0}", _Foo.GetSomeValue()); }
}

class FooBar : IFooBar {
    private readonly IFoo _Foo;
    private readonly IBar _Bar;

    public Bar(IFoo foo, IBar bar) { _Foo = foo; _Bar = bar; }
    public void FooAndBar() {
        _Foo.FooMe();
        _Bar.BarMe();
    }
}

// bindings
kernel.Bind<IFoo>().To<Foo>();
kernel.Bind<IBar>().To<Bar>();
kernel.Bind<IFooBar>().To<FooBar>();
//抽象
接口IFoo{
void FooMe();
int GetSomeValue();
}
接口IBar{
void BarMe();
}
接口IFooBar{
void FooAndBar();
}
//具体类别
Foo类:IFoo{
public void FooMe(){Console.WriteLine(“我有foood”);}
public void GetSomeValue(){return 123;}
}
分类栏:IBar{
私有只读iFooFoo;
公共酒吧(ifoofoo){ufoo=foo;}
public void BarMe(){Console.WriteLine(“Bar:{0},_Foo.GetSomeValue());}
}
类FooBar:IFooBar{
私有只读iFooFoo;
专用只读IBar\u条;
公共酒吧(IFoo-foo,IBar-Bar){u-foo=foo;{u-Bar=Bar;}
公共图书馆{
_Foo.FooMe();
_Bar.BarMe();
}
}
//绑定
kernel.Bind().To();
kernel.Bind().To();
kernel.Bind().To();
我想做的是设置它,每次我
kernel.Get
它都会创建一个Foo,并将其注入到Bar和FooBar的构造函数中

我曾经使用命名的范围扩展断断续续地尝试过这种方法,但我一直无法让它发挥作用


正确的绑定语法是什么?

因此,您要做的是定义一些名称:

const string FooBarScopeName = "FooBarScope";
然后定义范围:

kernel.Bind<IFooBar>().To<FooBar>()
      .DefinesNamedScope(FooBarScopeName);

备选方案:

还有一个
InCallScope()
,如果有一个
kernel.Get()
,每次创建
IFooBar
时都可以使用它。在这种情况下,只需执行以下操作:

kernel.Bind<IFoo>().To<Foo>().InCallScope();
kernel.Bind().To().InCallScope();

…在我看来,你似乎想要
在SingletonScope
。。。不是这样吗?不,每次我调用Get获取IFooBar时,我都需要Foo、Bar和FooBar的新实例,但Bar和FooBar之间只共享一个Foo。InCallScope似乎可以满足我对这个特定应用程序的需求。我整理了一个完整的测试项目,并对它进行了修改。我想我之前遇到的命名作用域的问题是,一旦开始使用它们,就会创建很多。至少对我来说是这样。这看起来太不雅观了,我想一定有更好的办法。
kernel.Bind<IFoo>().To<Foo>().InCallScope();