1.建立控制台项目并添加Nuget包引用
Nuget包:Microsoft.Extensions.DependencyInjection
2.简单使用asp.net
class Program { static void Main(string[] args) { // 正常使用 Bird bird = new Bird(); //IFly bird=new Bird(); bird.Fly(); //IOC使用 ServiceCollection serviceCollection = new ServiceCollection(); //建立IOC容器 serviceCollection.AddTransient<IFly, Bird>(); //将服务注入容器 var provider = serviceCollection.BuildServiceProvider(); //建立Provider var fly = provider.GetService<IFly>(); //获取注入的类型 fly.Fly(); //调用 } } interface IFly { void Fly(); } class Bird : IFly { public void Fly() { Console.WriteLine("鸟飞起来了........"); } }
3.日志注册ide
class Program { static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection(); //注册日志服务 serviceCollection.AddLogging(configure => configure.AddConsole() ); serviceCollection.AddTransient<IFly, Bird>(); var provider = serviceCollection.BuildServiceProvider(); provider.GetService<ILoggerFactory>(); var fly = provider.GetService<IFly>(); fly.Fly(); } } interface IFly { void Fly(); } class Bird : IFly { private readonly ILogger<Bird> _iLogger; public Bird(ILoggerFactory logger) { _iLogger = logger.CreateLogger<Bird>(); } public void Fly() { _iLogger.Log(LogLevel.Information, "日志消息....."); Console.WriteLine("鸟飞起来了........"); } }
4.生命周期函数
AddScoped案例代码ui
class Program { static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection(); ////每次请求都建立 //serviceCollection.AddTransient<IFly, Bird>(); ////单例模式,永远都是一个 //serviceCollection.AddSingleton<IFly, Bird>(); //在某个做用域下是单例 serviceCollection.AddScoped<IFly, Bird>(); var provider = serviceCollection.BuildServiceProvider(); //建立两个scope var scope1 = provider.CreateScope(); var scope2 = provider.CreateScope(); //第一个做用域 scope1.ServiceProvider.GetService<IFly>(); //第二个做用域 scope2.ServiceProvider.GetService<IFly>(); //第三个做用域 注意:这里是获取了两次 var fly = provider.GetService<IFly>();//第一次 fly = provider.GetService<IFly>();//第二次 fly.Fly(); } } interface IFly { void Fly(); } class Bird : IFly { public Bird() { Console.WriteLine("初始化构造函数......"); } public void Fly() { Console.WriteLine("鸟飞起来了........"); } }
运行结果:调用了三次构造函数.....net