首页 > 解决方案 > 在 C# 中注入依赖项

问题描述

我有一个机场课程,飞机物体可以根据天气起飞和降落。如果是暴风雨,他们不能起飞/降落,如果是晴天,他们可以。我有以下机场构造函数:

public string AirportName { get; set; }
public List<Plane> planes;

public Airport(string airportName)
{
    planes = new List<Plane>();
    AirportName = airportName;
    Weather weather = new Weather(); 
}

我有一个随机天气的天气类:

public class Weather
{
    public Weather()
    {
    }

    public string Forecast()
    {
        Random random = new Random();
        var weather = random.Next(1, 11);
        if (weather == 1 || weather == 2)
        {
            return "stormy";
        }
        else
        {
            return "sunny";
        }
    }
}

这就是我使用美因机场的方式:

static void Main()
{
    var gatwick = new Airport("London Gatwick");
}

由于天气信息是由一个单独的类提供的,我想将它作为依赖项注入到 Airport 中。但是,我在 C# 中很难做到这一点,因为我对这门语言真的很陌生。会不会是这样的:public Airport(string airportName, Weather weather)

如果有人能帮助我理解如何作为依赖注入以及如何在 Main.js 中调用它,我将不胜感激。谢谢!

标签: c#

解决方案


我建议您使用依赖注入库,例如Ninject

然后,您必须使用 Dependency Resolver 实例化您的类。

private readonly Weather weather;
public string AirportName { get; set; }
public List<Plane> planes;    

public Airport(string airportName, Weather weather)
{
    planes = new List<Plane>();
    AirportName = airportName;
    weather = weather; 
}

然后在你的主课上

   IKernel kernel = new StandardKernel();
   kernel.Bind<Airport>().
    To<Airport>().
    WithConstructorArgument("airportName", "Houston Airport");
   var warrior = kernel.Get<Airport>();

或者,如果您想在实例化时指定参数,请从上面删除“WithConstructorArgument”并执行以下操作:

   kernel.Get<Airport>( new ConstructorArgument( "airportName", "Houston Airport") );

推荐阅读