首页 文章

Ninject Factory自定义实例提供程序

提问于
浏览
2

我正在使用Ninject Factory Extension并在wiki中解释创建自定义实例提供程序:

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

我已经定义了以下工厂界面:

interface IFooFactory
{
    IFoo NewFoo(string template);
}

我创建了以下绑定:

kernel.Bind<IFooFactory>().ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
kernel.Bind<IFoo>().To<FooBar>().Named("Foo");

现在,当我调用以下内容时,我将获得 FooBar 的实例:

var foobar = fooFactory.NewFoo("Foo");

一切都很好 . 但我想要的是更像这样的东西:

interface IFooTemplateRepository
{
     Template GetTemplate(string template);
}

我有一个存储库,它将根据名称(“Foo”)返回一个模板,我想将模板作为构造函数参数传递 .

public class FooBar
{
    public FooBar(Template template)
    {
    }
}

这可能吗?我不确定应该依赖ITemplateRepository .

1 回答

  • 1

    不要使用IoC容器来创建实体的实例 . 这是业务逻辑,因此它不属于组合根目录 . 处理此问题的正确方法是直接使用ORM(例如,使用您正在使用的存储库模式) .

    var template = this.templateRepository.Get("SomeTemplate");
    var fooBar = this.fooBarFactory.CreateFooBar(template);
    

相关问题