【问题标题】:Ninject Factory on Derived TypesNinject Factory 派生类型
【发布时间】:2012-02-23 15:34:18
【问题描述】:

我正在查看以下链接中的 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?

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

【问题讨论】:

    标签: ninject ninject-extensions


    【解决方案1】:

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

        [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-10-23
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多