派生类型上的 Ninject 工厂

标签 ninject ninject-extensions

我正在通过以下链接查看 Ninject Factory 扩展: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

我正在尝试研究扩展程序,看看它是否真的适合我想要做的事情。

工厂扩展可以根据传入的参数创建不同的类型吗?

示例:

class Base {}
class Foo : Base {}
class Bar : Base {}

interface IBaseFactory
{
    Base Create(string type);
}

kernel.Bind<IBaseFactory>().ToFactory();

我想要做的是:

factory.Create("Foo") // returns a Foo
factory.Create("Bar") // returns a Bar
factory.Create("AnythingElse") // returns null or throws exception?

这个扩展可以做到这一点还是这不是真正的预期用途之一?

最佳答案

当然 - 您可以使用自定义实例提供程序。

    [Fact]
    public void CustomInstanceProviderTest()
    {
        const string Name = "theName";
        const int Length = 1;
        const int Width = 2;

        this.kernel.Bind<ICustomizableWeapon>().To<CustomizableSword>().Named("sword");
        this.kernel.Bind<ICustomizableWeapon>().To<CustomizableDagger>().Named("dagger");
        this.kernel.Bind<ISpecialWeaponFactory>().ToFactory(() => new UseFirstParameterAsNameInstanceProvider());

        var factory = this.kernel.Get<ISpecialWeaponFactory>();
        var instance = factory.CreateWeapon("sword", Length, Name, Width);

        instance.Should().BeOfType<CustomizableSword>();
        instance.Name.Should().Be(Name);
        instance.Length.Should().Be(Length);
        instance.Width.Should().Be(Width);
    }

    private class UseFirstParameterAsNameInstanceProvider : StandardInstanceProvider
    {
        protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments)
        {
            return (string)arguments[0];
        }

        protected override Parameters.ConstructorArgument[] GetConstructorArguments(System.Reflection.MethodInfo methodInfo, object[] arguments)
        {
            return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
        }
    }

关于派生类型上的 Ninject 工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416132/

相关文章:

c# - 依赖注入(inject)的最佳实践

Azure worker 角色 + Ninject + Quartz

ninject - 寻找行为类似于 InRequestScope 的 Ninject 范围

c# - 通用接口(interface)依赖注入(inject)到工厂

c# - Ninject Kernel.Get 和构造函数注入(inject)之间的不同行为

c# - 在 Ninject 中拦截实例的创建

Ninject 使用 BindToFactory 按约定绑定(bind)到具有类 T 的工厂接口(interface)

asp.net-mvc-4 - 将 Ninject 和 Ninject.Extensions.Conventions 与引用的程序集一起使用

scope - 无法弄清楚为什么 Ninject 命名范围没有按预期工作