1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DI

Posted at

いつもなんとなく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();
        }
    }
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?