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

标签 c# ninject

在我的应用程序中,有必要创建依赖于它们所使用的对象类型的接口(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/

相关文章:

c# - 使用 Ninject 在具有多个具有相同基本类型的存储库的类中分配正确的存储库

c# - Windows 似乎无法跟踪 .NET 应用程序

c# - 组框 WPF 内控件的可见性设置问题

ioc-container - 在 Ninject 2.0 中,我如何同时拥有通用绑定(bind)和特定情况的绑定(bind)?

Ninject 不在 WCF 中使用构造函数参数创建新实例

asp.net - 如何在 ASP.NET 中将 IHttpClientFactory 添加到 NInject

asp.net-mvc - 如何在 Ninject 中创建根据请求的 Controller 而变化的绑定(bind)?

c# - 单元测试事件处理程序

c# - 在 Xamarin.Android/Xamarin.iOS 中使用 Akavache

c# - 让程序在每次引发异常时发出蜂鸣声