在我的应用程序中,有必要创建依赖于它们所使用的对象类型的接口(interface)实现。为此,我决定实现 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 的全面描述,或者我无法找到它 - 所以我不知道如何从中获取类型。
最佳答案
您可以通过IContext.Request.Target
获取注入(inject)的目标:
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 的更多信息.
关于c# - 如何从 Ninject 中的 IContext 中提取有关作为注入(inject)目标的对象的确切类型的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680083/