我在以下链接中查看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?
此扩展程序可以执行此操作,还是这不是预期用途之一?
答案 0 :(得分:3)
当然 - 您可以使用自定义实例提供程序。
[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();
}
}