简体   繁体   English

使用Ninject使用构造函数参数实例化新对象

[英]Instantiating a new object with Constructor parameters using Ninject

I'm trying to refactor some code to use IoC with the Ninject framework. 我正在尝试重构一些代码以在Ninject框架中使用IoC。 So far I have managed to successfully inject in classes in scenarios where I do not have any constructor parameters to pass. 到目前为止,在没有任何构造函数参数可以传递的情况下,我已经成功地将类插入了。 However I am having difficulties when it comes to passing in parameters. 但是,在传递参数方面我遇到了困难。 This is the third binding in the binding class below. 这是下面的绑定类中的第三个绑定。

Binding Class 绑定类

public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<ILogger>().To<Logger>();
            Bind<IPlayerDatadao>().To<PlayerDatadao>();
            Bind<IPlayerScores>().To<PlayerScores>();
        }
    }

The logger class has a parameterless constructor and works fine when transferred to Ninject. logger类具有无参数构造函数,并且在传输到Ninject时可以正常工作。

Success 成功

    // IoC creation
    var kernel = new StandardKernel();
    kernel.Load(Assembly.GetExecutingAssembly());

    //Log User details
    var logger = kernel.Get<ILogger>();
    logger.LogVisitorDetails();

However, my attempt below threw an exception 但是,我的以下尝试引发了异常

Failure 失败

        string priceString = Foo();
        string pointsString = Bar();

        return kernel.Get<IPlayerScores>(new[] { new ConstructorArgument("pointsString", pointsString), new ConstructorArgument("points", priceString) });

This is the class with its constructor. 这是带有其构造函数的类。

Class to Inject 注射类

public class PlayerScores : IPlayerScores
{
    [Inject]
    public string points { get; set; }
    [Inject]
    public string price { get; set; }
    public PlayerScores(string Points, string Price)
    {
        points = Points;
        price = Price;
    }
}

I'm really not sure how I should be handling the parameters either in the binding class or at the point of injection 我真的不确定在绑定类或注入时应该如何处理参数

I'm really not sure how I should be handling the parameters either in the binding class or at the point of injection 我真的不确定在绑定类或注入时应该如何处理参数

At binding. 在绑定。 You should remove any Ninject dependencies from your model: 您应该从模型中删除所有Ninject依赖项:

public class PlayerScores : IPlayerScores
{
    public PlayerScores(string points, string price)
    {
        this.Points = points;
        this.Price = price;
    }

    public string Points { get; set; }
    public string Price { get; set; }
}

and then configure the kernel: 然后配置内核:

Bind<IPlayerScores>()
    .To<PlayerScores>()
    .WithConstructorArgument("points", "some points")
    .WithConstructorArgument("price", "some price");

or using ToMethod which is a bit more refactor friendly as it avoids the magic strings with the parameter names: 或使用更加重构友好的ToMethod ,因为它避免了带有参数名称的魔术字符串:

Bind<IPlayerScores>()
    .ToMethod(ctx => new PlayerScores("some points", "some price"));

This being said, if the 2 parameters are so volatile that they need to have a different value on each call, then you probably should not be passing them as constructor parameters but rather as parameters to some instance method that you would invoke on the class at runtime. 就是说,如果这两个参数非常不稳定,以至于每个调用它们都需要具有不同的值,那么您可能不应该将它们作为构造函数参数传递,而是作为参数传递给某个实例方法,该实例方法将在以下位置在类中调用运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Ninject在构造函数中使用其他参数创建实例 - Creating an instance using Ninject with additional parameters in the constructor WPF Ninject与Datacontext和构造函数与参数 - WPF Ninject with Datacontext and constructor with parameters 为什么在构造函数中实例化新对象之前检查类变量是否为null? - Why check if a class variable is null before instantiating a new object in the constructor? 实例化一个对象,但使用大括号而不是默认构造函数? - Instantiating an object, but using curly brackets instead of the default constructor? NInject:用两个参数解决构造函数注入 - NInject: Resolve constructor injection with two parameters 在Ninject中使用无参数控制器构造函数? - Using a parameterless controller constructor with Ninject? 使用Ninject进行过滤器构造函数注入 - Filter constructor injection using Ninject 使用反射在内部类中使用参数实例化构造函数 - Instantiating a constructor with parameters in an internal class with reflection 在 .NET Core 中实例化新对象,这些对象在其构造函数中使用依赖注入而不使用 new - Instantiating new objects in .NET Core that use dependency injection in their constructor without using new Ninject:将构造函数参数绑定到其他对象的属性 - Ninject: Bind Constructor Argument to Property of Other Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM