c# - 在 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 中调用它,我将不胜感激。谢谢!
解决方案
我建议您使用依赖注入库,例如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") );
推荐阅读
- laravel - 查询生成器写入 sql 'WHERE total = %s' % (n,)
- boost - BOOST TLS连接建立使用服务器和客户端之间交换数据后的boost
- excel - 遍历文件夹 vba
- flutter - 移动设备的 Flutter Web 桌面视图 | 颤振网络
- html - 如何使用相对于标题的 rvest 在维基百科中刮取有序和无序列表
- forms - 如何在 Colab 中从数组中添加表单元素
- flutter - 如何测试依赖于 Flutter 服务的服务
- spring-boot - 无法同时使用“https://start.spring.io”和“http://start.spring.io”创建 Spring Starter 项目
- angular - 在延迟加载的模块中提供服务
- python - 如何一起使用两个 async def