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