使用相同的接口注册两个相同类型的单例实例

Registering two singleton instances of same type using same interface

我需要在 Ninject、

中使用相同的接口注册两个相同类型的单例实例

对于

kernel.Bind<IManifest>().To<Manifest>().InSingletonScope(); // first instance
kernel.Bind<IManifest>().To<Manifest>().InSingletonScope(); // second one

我怎样才能做到这一点?我希望应该有一些方法可以使用一些 属性 或其他东西来区分它们..

您可以使用命名语法:

kernel.Bind<IManifest>().To<Manifest>().InSingletonScope().Named("ManifestA");
kernel.Bind<IManifest>().To<Manifest>().InSingletonScope().Named("ManifestB");

然后通过调用检索它:

kernel.Get<IWeapon>("ManifestA");

或在构造函数中指定 NamedAttribute。

public class ParentA
{
    public ParentA([Named("ManifestA")] IManifest manifest)
    {
        ....
    }
}

那么你也可以使用 WhenInjectedInto 语法。

kernel.Bind<IManifest>().To<Manifest>().WhenInjectedInto<ParentA>().InSingletonScope();
kernel.Bind<IManifest>().To<Manifest>().WhenInjectedInto<ParentB>().InSingletonScope();

或 WhenParentNamed 语法,如果 Parents 是同一类型:

kernel.Bind<Parent>().ToSelf().Named("ParentA");
kernel.Bind<Parent>().ToSelf().Named("ParentB");

kernel.Bind<IManifest>().To<Manifest>().WhenParentNamed("ParentA").InSingletonScope();
kernel.Bind<IManifest>().To<Manifest>().WhenParentNamed("ParentB").InSingletonScope();