.NET Core 依赖注入-1

1.依赖注入(Dependency Injection,DI)是控制反转(Inversion Of Control,IOC)思想的实现方式。依赖注入简化模块的组装过程,降低模块质检的耦合度
需要引用到的NuGet包:Microsoft.Extensions.DependencyInjection
2.

  public interface ITestService
    {
        public int Age { get; set; }
        public string Name { get; set; }
        void SayHi();
    }
	public class TestService : ITestService
    {
        public int Age { get; set; }
        public string Name { get; set; }

        public void SayHi()
        {
            Console.WriteLine(Name + Age);
        }
    }

  ServiceCollection Services = new ServiceCollection();
  //生命周期分为三种 Transient(瞬时)、Scope(作用域,推荐)、Singleton(单例)
Services.AddTransient<ITestService, TestService>();
//Services.AddTransient<typeof(ITestService), ty7peof(TestService)>();
//Services.AddTransient<typeof(ITestService), new TestService()>();
using (ServiceProvider provider = Services.BuildServiceProvider())
{
   //T GetService<T>() 获取不到对象会返回null
   // T GetRequiredService<T>() 获取不到对象会抛出异常
   // IEnumerable<T>GetServices<T> 用于可能满足很多条件的服务
    var t = provider.GetService<ITestService>();
    t.Age = 111;
    t.Name = "ss";
    t.SayHi();

    var t2 = provider.GetService<ITestService>();
    t2.Age = 111;
    t2.Name = "ssdsfcxzs";
    t2.SayHi();
    t.SayHi();

    Console.WriteLine(object.ReferenceEquals(t, t2));
}

3.依赖注入具有传染性 如果一个类通过DI构造,那么这个类的构造函数中声明的所有服务器类型的参数都会被DI赋值

ServiceCollection services=new ServiceCollection();
services.AddScoped<ILog, ILogImpl>();
services.AddScoped<ILog, FileImpl>();
//同一个接口注入多个实现类 会被覆盖
services.AddScoped<IStorage, IStorageImpl>();
services.AddScoped<IController, Controller>();
using (ServiceProvider ServiceProvider = services.BuildServiceProvider())
{
   var CONTYROL=  ServiceProvider.GetService<IController>();

    CONTYROL.Test();

}


interface IController
{
    void Test();
}

class Controller : IController
{
    private readonly ILog log;
    private readonly IStorage storage;

    public Controller(ILog log, IStorage storage)
    {
        this.log = log;
        this.storage = storage;
    }

    public void Test()
    {
        log.WriteLog("ssssssss");
        storage.WriteLog("2222222222");
    }
}
interface ILog
{
    void WriteLog(string content);
}
class ILogImpl : ILog
{
    public void WriteLog(string content)
    {
        Console.WriteLine($"记录日志信息:{content}");
    }
}
class FileImpl : ILog
{
    public void WriteLog(string content)
    {
        Console.WriteLine($"通过文件记录日志信息:{content}");
    }
}

interface IStorage
{
    void WriteLog(string content);
}
class IStorageImpl : IStorage
{
    public void WriteLog(string content)
    {
        Console.WriteLine($"上传文件到云盘:{content}");
    }
}
posted @ 2022-06-29 11:25  Wilson_it  阅读(58)  评论(0编辑  收藏  举报