Ninject工厂派生类型 [英] Ninject Factory on Derived Types

查看:84
本文介绍了Ninject工厂派生类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

示例:

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?

此扩展程序可以执行此操作吗,或者这不是预期用途吗?

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

推荐答案

可以-您可以使用自定义实例提供程序.

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

这篇关于Ninject工厂派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆