いつもなんとなくDIしてるので、基本をメモ
public interface IGetWeather
{
public string GetWeather();
}
internal class GetSunny: IGetWeather
{
public string GetWeather()
{
return "晴れ";
}
}
internal class GetRain : IGetWeather
{
public string GetWeather()
{
return "雨";
}
}
internal class GetMessage
{
private IGetWeather getWeather;
public GetMessage(IGetWeather getWeather)
{
this.getWeather = getWeather;
}
public void ShowMessage()
{
Console.WriteLine(getWeather.GetWeather());
}
}
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddTransient<IGetWeather, GetSunny>();
services.AddTransient<GetMessage>();
var provider = services.BuildServiceProvider();
var message = provider.GetRequiredService<GetMessage>();
message.ShowMessage();
}
}