C# 如何从Ninject中的IContext中提取有关作为注入目标的对象的确切类型的信息?
在我的应用程序中,有必要创建接口的实现,这取决于它们所使用的对象的类型。为此,我决定植入SimpleProvider的后代,在经典的Ninject示例中应该是这样的:C# 如何从Ninject中的IContext中提取有关作为注入目标的对象的确切类型的信息?,c#,ninject,C#,Ninject,在我的应用程序中,有必要创建接口的实现,这取决于它们所使用的对象的类型。为此,我决定植入SimpleProvider的后代,在经典的Ninject示例中应该是这样的: public class MyProvider: Provider<IWeapon> { protected override IWeaponCreateInstance(IContext context) { //if the weapon user is of type samura
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;
}
}
公共类MyProvider:Provider
{
受保护的覆盖IweAppOnCreateInstance(IContext上下文)
{
//如果武器使用者是武士类型
{
返回新的武士刀();
}
//如果武器使用者实施IHorseman
{
返回Kernel.Get();
}
回归新剑;
}
}
在我的特定情况下,我想使用LogManager.GetLogger(type.FullName)。
我的问题是缺乏对IContext的全面描述,或者我无法找到它,因此我不知道如何从中获取类型。您可以使用
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;
}
}
公共类MyProvider:Provider
{
受保护的覆盖IweAppOnCreateInstance(IContext上下文)
{
if(context.Request.Target.Type==typeof(武士))
{
返回新的武士刀();
}
if(typeof(IHorseman).IsAssignableFrom(context.Request.Target.Type))
{
返回Kernel.Get();
}
回归新剑;
}
}
您可以阅读更多关于。我衷心感谢您。这正是我需要的。