C#依赖注入

参考博客园文档:

https://www.cnblogs.com/sunpan/p/14244062.html

nuget 安装依赖包(nuget 使用源路径:https://www.nuget.org/api/v2/)

 

 

 

 按照参考文件直接编写程序如下:

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using Microsoft.Extensions.DependencyInjection;
 8 
 9 namespace TestDI
10 {
11     //定义接口
12     public interface IFoobar 
13     {
14         void Show();
15     }
16     class Foo : IFoobar
17     {
18         public void Show()
19         {
20             Console.WriteLine("Foo Show func...");
21         }
22     }
23     class Bar : IFoobar
24     { 
25         public void Show()
26         {
27             Console.WriteLine("Bar Show func...");
28         }
29     }
30 
31     class Program
32     {
33         static void Main(string[] args)
34         {
35             var scol = new ServiceCollection()
36                 .AddSingleton<IFoobar, Foo>()
37                 .AddSingleton<IFoobar, Bar>();
38             
39             IServiceProvider service_pro = scol.BuildServiceProvider();
40             Console.WriteLine("serviceProvider.getservice():{0}", service_pro.GetService<IFoobar>());
41 
42             IEnumerable<IFoobar> services = service_pro.GetServices<IFoobar>();
43             Console.WriteLine("serviceProvider.getservices():");
44             foreach (var fb in services)
45             {
46                 fb.Show();
47                 Console.WriteLine("{0}",fb);
48             }
49 
50             Console.ReadKey();
51         }
52     }
53 }

 

posted @ 2022-09-16 13:30  小小林林  阅读(102)  评论(0编辑  收藏  举报