如何从Ninject中的IContext中提取有关作为注入目标的确切对象类型的信息?

时间:2012-03-13 07:43:30

标签: c# ninject

在我的应用程序中,有必要创建依赖于它们所使用的对象类型的接口实现。为此,我决定实现SimpleProvider的后代,就经典Ninject示例而言应该去像:

public class MyProvider: Provider<IWeapon>
{
    protected override IWeaponCreateInstance(IContext context)
    {
        //if the weapon user is of type samurai
        {
             return new Katana();
        }
        //if the weapon user implements IHorseman
        {
             return Kernel.Get<IHorsemanWeapon>();
        }
        return new Sword;
    }
}

在我的具体情况下,我想使用LogManager.GetLogger(type.FullName)。 对我来说问题是缺乏对IContext的全面描述或者我无法找到它 - 所以我不知道如何从中获取类型。

1 个答案:

答案 0 :(得分:3)

您可以使用IContext.Request.Target获取注射目标:

public class MyProvider: Provider<IWeapon>
{
    protected override IWeaponCreateInstance(IContext context)
    {
        if (context.Request.Target.Type == typeof(Samurai))
        {
             return new Katana();
        }
        if (typeof(IHorseman).IsAssignableFrom(context.Request.Target.Type))
        {
             return Kernel.Get<IHorsemanWeapon>();
        }
        return new Sword;
    }
}

您可以阅读有关Contextual bindings的更多信息。

相关问题