Ninject工厂自定义实例提供程序
我正在使用Ninject Factory扩展并创建一个自定义实例提供程序,在wiki中进行了解释:Ninject工厂自定义实例提供程序,ninject,ninject-extensions,Ninject,Ninject Extensions,我正在使用Ninject Factory扩展并创建一个自定义实例提供程序,在wiki中进行了解释: class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider { protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments) { return (strin
class UseFirstArgumentAsNameInstanceProvider : 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();
}
}
我定义了以下factory接口:
interface IFooFactory
{
IFoo NewFoo(string template);
}
我创建了以下绑定:
kernel.Bind<IFooFactory>().ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
kernel.Bind<IFoo>().To<FooBar>().Named("Foo");
这一切都很好。然而,我想要的是更像这样的东西:
interface IFooTemplateRepository
{
Template GetTemplate(string template);
}
我有一个存储库,它将根据名称(“Foo”)返回一个模板,我希望将该模板作为构造函数参数传递
public class FooBar
{
public FooBar(Template template)
{
}
}
这可能吗?我不确定什么应该依赖于ITemplateRepository。不要使用IoC容器创建实体实例。这是业务逻辑,因此它不属于组合根。正确的处理方法是直接使用ORM(例如,使用您正在使用的存储库模式)
我觉得我想得太多了。我可能会创建一个自定义提供程序,将第一个参数转换为模板,并检查其中的属性以确定要创建的命名实例。
public class FooBar
{
public FooBar(Template template)
{
}
}
var template = this.templateRepository.Get("SomeTemplate");
var fooBar = this.fooBarFactory.CreateFooBar(template);