在.NET Core中处理一个接口多个不同实现的依赖注入问题

一、构造函数注入一个接口集合

Startup.cs

1
2
3
4
5
6
public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<ICar, BaoMa>();
            services.AddScoped<ICar, BenChi>();
            services.AddSingleton<ICar, AoDi>();
        }

 接口和类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public interface ICar
{
    string GetName(string n);
}
 
public class BenChi : ICar
{
    private Guid g;
    public BenChi()
    {
        g = Guid.NewGuid();
    }
    public string GetName(string n)
    {
        return "我是奔驰,我的主人是" + n + ",guid:" + g;
    }
}
 
public class AoDi : ICar
{
    private Guid g;
    public AoDi()
    {
        g = Guid.NewGuid();
    }
    public string GetName(string n)
    {
        return "我是奥迪,我的主人是" + n + ",guid:" + g;
    }
}
 
public class BaoMa : ICar
{
    private Guid g;
    public BaoMa()
    {
        g = Guid.NewGuid();
    }
 
    public string GetName(string n)
    {
        return "我是宝马,我的主人是" + n + ",guid:" + g;
    }
}

/Controllers/AboutController.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class AboutController : Controller
    {
        private ICar baoma;
        private ICar benchi;
        private ICar aodi;
 
        public AboutController(IEnumerable<ICar> cars)
        {
            this.baoma = cars.FirstOrDefault(h => h.GetType().Name == "BaoMa");
            this.benchi = cars.FirstOrDefault(h => h.GetType().Name == "BenChi");
            this.aodi = cars.FirstOrDefault(h => h.GetType().Name == "AoDi");
        }
 
        public IActionResult Index()
        {
            ViewData["BaoMa"] = baoma;
            ViewData["BenChi"] = benchi;
            ViewData["AoDi"] = aodi;
            return View();
        }
    }

/Views/About/Index.cshtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@{
    ViewData["Title"] = "About Page";
}
@using  yilaizhuru2.Car
@inject IEnumerable<ICar> cars
 
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <p>@((ViewData["BaoMa"] as BaoMa).GetName("BaoMa"))</p>
    <p>@((ViewData["BenChi"] as BenChi).GetName("BenChi"))</p>
    <p>@((ViewData["AoDi"] as AoDi).GetName("AoDi"))</p>
    <hr />
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "BaoMa").GetName("BaoMa")</p>
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "BaoMa").GetName("BaoMa")</p>
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "BenChi").GetName("BenChi")</p>
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "BenChi").GetName("BenChi")</p>
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "AoDi").GetName("AoDi")</p>
    <p>@cars.FirstOrDefault(h => h.GetType().Name == "AoDi").GetName("AoDi")</p>
</div>

  

二、利用AddTransient的扩展方法

Startup.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<Apple>();
            services.AddScoped<Banana>();
            services.AddSingleton<Watermelon>();
            //https://blog.csdn.net/qin_yu_2010/article/details/86150218
            //注意改成AddTransient,AddSingleton会报错Cannot resolve scoped service 'yilaizhuru2.BenChi' from root provider
            services.AddTransient(factory =>
            {
                Func<string, IFruit> accesor = key =>
                {
                    if (key.Equals("Apple"))
                    {
                        return factory.GetService<Apple>();
                    }
                    else if (key.Equals("Banana"))
                    {
                        return factory.GetService<Banana>();
                    }
                    else if (key.Equals("Watermelon"))
                    {
                        return factory.GetService<Watermelon>();
                    }
                    else
                    {
                        throw new ArgumentException($"Not Support key : {key}");
                    }
                }; return accesor;
            });
        }

接口和类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public interface IFruit
{
    string GetName(string n);
}
 
public class Watermelon : IFruit
{
    private Guid g;
    public Watermelon()
    {
        g = Guid.NewGuid();
    }
    public string GetName(string n)
    {
        return "我是西瓜,我的主人是" + n + ",guid:" + g;
    }
}
 
public class Banana : IFruit
{
    private Guid g;
    public Banana()
    {
        g = Guid.NewGuid();
    }
 
    public string GetName(string n)
    {
        return "我是香蕉,我的主人是" + n + ",guid:" + g;
    }
}
 
public class Apple : IFruit
{
    private Guid g;
    public Apple()
    {
        g = Guid.NewGuid();
    }
    public string GetName(string n)
    {
        return "我是苹果,我的主人是" + n + ",guid:" + g;
    }
}

/Controllers/HomeController.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class HomeController : Controller
{
    private readonly Func<string, IFruit> _serviceAccessor;
    private IFruit apple;
    private IFruit banana;
    private IFruit watermelon;
 
    public HomeController(Func<string, IFruit> serviceAccessor)
    {
        this._serviceAccessor = serviceAccessor;
        this.apple = _serviceAccessor("Apple");
        this.banana = _serviceAccessor("Banana");
        this.watermelon = _serviceAccessor("Watermelon");
    }
 
    public IActionResult Index()
    {
        ViewData["Apple"] = apple;
        ViewData["Banana"] = banana;
        ViewData["Watermelon"] = watermelon;
        return View();
    }
}

/Views/Home/Index.cshtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@{
    ViewData["Title"] = "Home Page";
}
@using  yilaizhuru2.Fruit
@inject Func<string, IFruit> _serviceAccessor
 
 
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <p>@((ViewData["Apple"] as Apple).GetName("Apple"))</p>
    <p>@((ViewData["Banana"] as Banana).GetName("Banana"))</p>
    <p>@((ViewData["Watermelon"] as Watermelon).GetName("Watermelon"))</p>
    <hr />
    <p>@_serviceAccessor("Apple").GetName("Apple")</p>
    <p>@_serviceAccessor("Apple").GetName("Apple")</p>
    <p>@_serviceAccessor("Banana").GetName("Banana")</p>
    <p>@_serviceAccessor("Banana").GetName("Banana")</p>
    <p>@_serviceAccessor("Watermelon").GetName("Watermelon")</p>
    <p>@_serviceAccessor("Watermelon").GetName("Watermelon")</p>
</div>

  

参考:

https://www.cnblogs.com/yilezhu/p/10236163.html

https://mp.weixin.qq.com/s/e4mO5hJ1qbBk87N41ErdfA?

posted @   阿水zev  阅读(945)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示