Ninject Factory on Derived Types

浪子不回头ぞ 提交于 2020-01-01 17:28:10

问题


I'm looking at the Ninject Factory extension at the following link: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

I'm trying to wrap my head around the extension and see if it actually fits into what I'm trying to do.

Can the factory extension create different types based on a parameter that is passed in?

Example:

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

interface IBaseFactory
{
    Base Create(string type);
}

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

What I want to be able to do is this:

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

Can this extension do this or is this not really one of the intended uses?


回答1:


Sure - You can use your custom instance provider.

    [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();
        }
    }


来源:https://stackoverflow.com/questions/9416132/ninject-factory-on-derived-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!