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