2

次のリンクでNinjectFactory拡張機能を見ています: 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?

この拡張機能はこれを行うことができますか、それともこれは実際には意図された用途の1つではありませんか?

4

1 に答える 1

3

確かに-カスタムインスタンスプロバイダーを使用できます。

    [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();
        }
    }
于 2012-02-23T17:05:16.077 に答える