【问题标题】:Passing parent constructor arguments to nested class constructor with Ninject使用 Ninject 将父构造函数参数传递给嵌套类构造函数
【发布时间】:2015-09-23 13:29:20
【问题描述】:

我试图让 ninject 使用来自父类的构造函数参数,并在实例化时将其作为参数传递给子类。我将如何进行绑定以使其正确发生?我一直在浏览这些示例,但没有找到解决方案。

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<ParentClass>().ToSelf();
        Bind<ChildClass>().ToSelf();
    }
}

public class ParentClass
{
    private string _index;
    private ChildClass _childClass;

    public ParentClass(string index, ChildClass childClass)
    {
        _index = index;
        _childClass = childClass;
    }
}

public class ChildClass
{
    private string _index;

    public ChildClass(string index)
    {
        _index = index;
    }

    public string Index { get; set; }
}

var kernel = new StandardKernel(new MyModule());
kernel.Get<ParentClass>(new ConstructorArgument("index", "MyIndex"));

所以当我创建我的 ParentClass 实例时,我希望里面的 ChildClass 具有相同的索引值。

【问题讨论】:

标签: c# ninject


【解决方案1】:

只需将要继承的参数更改为子请求,如下所示:

kernel.Get<ParentClass>(new ConstructorArgument("index", "MyIndex", true));

这样ConstructorArgument 适用于Get 调用实例化的所有对象。当然,ConstructorArgument 仅适用于具有匹配名称的构造函数参数。在您的情况下,ParentClassChildClass 的参数都命名为 index,所以它可以工作。

另见ConstructorArgument构造函数here的文档和IParameterhere的文档

更新

在较新的 Ninject 版本中,现在有 TypeMatchingConstructorArgument 匹配类型而不是参数名称。但是,如果它真的是像string 这样无处不在的类型,那么将配置值“包含”在一个新类型中会更有意义,如Joseph Evenson's answer 所示。

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,最初使用继承的构造函数参数解决方案,直到我的一位同事指出了缺点 - 如果您(或其他人)曾经更改构造函数参数名称(索引),您的应用程序将会中断。

    在继承中使用命名构造函数参数的另一种方法是创建一个配置类型,为此请求上下文创建一个新内核并将配置类型(针对该内核)绑定到一个常量。你最终会得到类似的东西:

    public class MyModule : NinjectModule
    {
        private string _index;
    
        public MyModule(string index)
        {
            _index = index;
        }
    
        public override void Load()
        {
            Bind<ConfigurationType>().ToConstant(new ConfigurationType(_index));
            Bind<ParentClass>().ToSelf();
            Bind<ChildClass>().ToSelf();
        }  
    }
    
    public class ParentClass
    {
        private string _index;
        private ChildClass _childClass;
    
        public ParentClass(ConfigurationType configuration, ChildClass childClass)
        {
            _index = configuration.Index;
            _childClass = childClass;
        }
    }
    
    public class ChildClass
    {
        private string _index;
    
        public ChildClass(ConfigurationType configuration configuration)
        {
            _index = configuration.Index;
        }
    
        public string Index { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2023-04-04
      相关资源
      最近更新 更多