gpt4 book ai didi

派生类型的 Ninject 工厂

转载 作者:行者123 更新时间:2023-12-04 05:56:49 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com