C# 之 简单的依赖注入代码示例

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {
            var sc = new ServiceCollection();               // 依赖注入需要的容器
            sc.AddScoped(typeof(IVehicle), typeof(Car));
            sc.AddScoped(typeof(ITank), typeof(LightTank));
            sc.AddScoped<GirlFriend>();
            var sp = sc.BuildServiceProvider();             // 对容器的控制

            // --------------------------------------------

            var driver = sp.GetService<IVehicle>();
            driver.Run();

            var t = sp.GetService<GirlFriend>();
            t.Work();
        }
    }

    // 接口隔离原则
    interface IVehicle
    {
        void Run();
    }

    class Car : IVehicle
    {
        public void Run()
        {
            Console.WriteLine("ci ci ci...");
        }
    }

    class GirlFriend
    {
        private IVehicle _vehicle;
        public GirlFriend(IVehicle Vehicle)
        {
            _vehicle = Vehicle;
        }

        public void Work()
        {
            _vehicle.Run();
        }
    }

    interface IFire
    {
        void Fire();
    }

    interface ITank : IVehicle, IFire
    {

    }

    class LightTank : ITank
    {
        public void Fire()
        {
            Console.WriteLine("bang! bang!...");
        }

        public void Run()
        {
            Console.WriteLine("ka! ka! ka!...");
        }
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42100963/article/details/107600657