C# 依赖注入简单例子

依赖注入简单例子

using System;
using Microsoft.Extensions.DependencyInjection;

class Program
{

    interface ITanGuan
    {
        void hello();
    }
    class TanGuan:ITanGuan
    {
        public int A{get;set;}
        public int B{get;set;}
        public TanGuan(IPower hs)
        {
            A = hs.GetA();
            B = hs.GetB();
        }

        void ITanGuan.hello()
        {
            System.Console.WriteLine("hello");
        }
    }

    interface IPower
    {
        int GetA();
        int GetB();
    }

    class Power:IPower
    {
        public int GetA()
        {
            return 30;
        }

        public int GetB()
        {
            return 56;
        }

    }

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddSingleton(typeof(ITanGuan), typeof(TanGuan));
        services.AddSingleton(typeof(IPower), typeof(Power));
        IServiceProvider serviceProvider = services.BuildServiceProvider();
        ITanGuan mything = serviceProvider.GetService<ITanGuan>();
    }
}

上面这段代码中,类TanGuan依赖接口IPower。从第15行可以看出,TanGuan类的构造器需要传入IPower接口。
Main()方法内,就是通过IServiceCollection依赖容器将TanGuan和Power这两个类注入到了容器内。
52行则是生成一个带有依赖容器的IServiceProvider 依赖提供者。
53行就是通过IServiceProvider 提供方的GetService()方法获取ITanGuan服务的实体。
我们可以通过调试发现mything这个实体可以成功获取到TanGuan类实体。说明依赖注入框架能自动识别TanGuan构造器传入的IPower为Power,这个过程看起来都是自动的。
有了这个依赖注入,客户端代码与服务供应商之间的代码可以做到非常松的耦合。
因为不同的接口服务的具体类的供应商可以自己实现自己的类,如果客户端想更换不同的接口服务,只需要修改50行和51行的代码。

同一接口多次注入

下面的例子演示了,GetService<IEnumerable<…>>()的方法:

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;

class Program
{

    interface ITanGuan
    {
        void hello();
    }
    class TanGuan:ITanGuan
    {
        public int A{get;set;}
        public int B{get;set;}
        public TanGuan(IPower hs)
        {
            A = hs.GetA();
            B = hs.GetB();
        }

        void ITanGuan.hello()
        {
            System.Console.WriteLine("hello");
        }
    }

    class TanGuan2:ITanGuan
    {
        void ITanGuan.hello()
        {
            System.Console.WriteLine("Hello 2");
        }        
    }

    interface IPower
    {
        int GetA();
        int GetB();
    }

    class Power:IPower
    {
        public int GetA()
        {
            return 30;
        }

        public int GetB()
        {
            return 56;
        }

    }

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddSingleton(typeof(ITanGuan), typeof(TanGuan));
        services.AddSingleton(typeof(ITanGuan), typeof(TanGuan2));
        services.AddSingleton(typeof(IPower), typeof(Power));
        IServiceProvider serviceProvider = services.BuildServiceProvider();
        IEnumerable<ITanGuan> mything = serviceProvider.GetService<IEnumerable<ITanGuan>>();
    }
}

依赖注入泛型接口

举例子:

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    public interface IHome<T>
    {
        List<T> GetList();
    }

    class Home<T> : IHome<T>
    {
        private List<T> _list;

        public Home()
        {
            _list = new List<T>();
        }
        public List<T> GetList()
        {
            return _list;
        }
    }

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddSingleton(typeof(IHome<>), typeof(Home<>)); // 注入泛型
        IServiceProvider serviceProvider = services.BuildServiceProvider();
        var d1 = serviceProvider.GetService<IHome<int>>(); // 获取服务IHome<int>
        List<int> list = d1.GetList();
        var d2 = serviceProvider.GetService<IHome<double>>(); // 获取服务IHome<double>
        List<double> lsit2 = d2.GetList();
    }
}

代码中有的:

services.AddSingleton(typeof(IHome<>), typeof(Home<>));

就是泛型接口的依赖注入。
在GetService()阶段,可以赋予不同的类型参数而产生不同的类型实例,显得非常高级。Asp.net Core中的ILogger<TCategoryName>接口就是这个注入原理。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,依赖注入是一种设计模式,用于将一个对象的依赖关系从它的客户端解耦。通过依赖注入,创建对象时,它所依赖的其他对象会被注入到它的构造函数、属性或方法中,从而实现对象之间的松耦合。 在C#中,可以使用构造方法注入和属性注入两种方式来实现依赖注入。 构造方法注入是在对象的构造方法中将依赖对象作为参数传入,例如: ```csharp internal class ClientClass { private IServiceClass _serviceImpl; public ClientClass(IServiceClass serviceImpl) { this._serviceImpl = serviceImpl; } // ... } ``` 属性注入是通过对象的属性来注入依赖对象,例如: ```csharp internal class ClientClass { public IServiceClass ServiceImpl { get; set; } // ... } ``` 需要注意的是,构造方法注入只能在实例化客户类时注入一次,而属性注入可以在程序运行期间改变客户类对象内的服务类实例。 为了实现依赖注入,通常需要使用一个依赖注入容器(例如:Microsoft.Extensions.DependencyInjection),通过容器来管理依赖对象的创建和注入。 除了依赖注入容器,还可以使用配置文件来管理依赖对象的创建和注入。可以使用ConfigurationBuilder类来导入配置文件,并使用IOptions<T>来获取配置文件中的内容。 总结起来,C#中的依赖注入是通过构造方法注入或属性注入来创建对象并将依赖对象注入其中。使用依赖注入容器可以更方便地管理依赖对象的创建和注入,而配置文件可以用于配置和管理依赖对象的属性值。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C#依赖注入](https://blog.csdn.net/qq_18145031/article/details/83181937)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [c#依赖注入](https://blog.csdn.net/wanxiweilai/article/details/127878160)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值