.net 依赖注入


theme: hydrogen

接口实现

相关代码

```

using System;

namespace ioc1 { class Program { static void Main(string[] args) { IService service = new ServiceImpl(); service.Name = "tom"; service.sayHi(); Console.Read(); }

public interface IService
    {
        public string Name { get; set; }

        public void sayHi();
    }

    public class ServiceImpl : IService
    {
        public string Name { get; set; }

        public void sayHi()
        {
            Console.WriteLine($"你好。我是{Name}");
        }
    }
}

} ```

运行结果

image.png

服务注册

下载DI包

image.png

相关代码

``` using Microsoft.Extensions.DependencyInjection; using System;

namespace ioc1 { class Program { static void Main(string[] args) {

/*IService service = new ServiceImpl();
        service.Name = "tom";
        service.sayHi();*/


        ServiceCollection services = new ServiceCollection();
        services.AddTransient<ServiceImpl>();
        // 使用using 防止资源泄漏
        using (ServiceProvider sp = services.BuildServiceProvider())
        {
            ServiceImpl t = sp.GetService<ServiceImpl>();
            t.Name = "zhangsan";
            t.sayHi();
        }
        Console.Read();
    }

    public interface IService
    {
        public string Name { get; set; }

        public void sayHi();
    }

    public class ServiceImpl : IService
    {
        public string Name { get; set; }

        public void sayHi()
        {
            Console.WriteLine($"你好。我是{Name}");
        }
    }
}

} ```

运行结果

image.png

服务定位器

相关代码

``` using Microsoft.Extensions.DependencyInjection; using System;

namespace ioc1 { class Program { static void Main(string[] args) {

ServiceCollection services = new ServiceCollection();

        services.AddScoped<IService, ServiceImpl>();

        // 使用using 防止资源泄漏
        using (ServiceProvider sp = services.BuildServiceProvider())
        {
            IService t = sp.GetService<IService>();
            t.Name = "lisi";
            t.sayHi();
        }
        Console.Read();
    }

    public interface IService
    {
        public string Name { get; set; }

        public void sayHi();
    }

    public class ServiceImpl : IService
    {
        public string Name { get; set; }

        public void sayHi()
        {
            Console.WriteLine($"你好。我是{Name}");
        }
    }
}

} ```

运行结果

image.png

demo

相关代码

``` using Microsoft.Extensions.DependencyInjection;

namespace di { class Program { static void Main(string[] args) { ServiceCollection services = new ServiceCollection(); services.AddScoped (); services.AddScoped (); services.AddScoped (); services.AddScoped ();

using(var sp = services.BuildServiceProvider())
        {
            Controller controller = sp.GetRequiredService<Controller>();
            controller.Test();
        }
        Console.ReadKey();
    }
}

class Controller
{
    private readonly ILog log;
    private readonly IStorage storage;
    public Controller(ILog log,IStorage storage)
    {
        this.log = log;
        this.storage = storage;
    }

    public void Test()
    {
        log.Log("开始上传");

        this.storage.Save("内容", "file.txt");

        log.Log("上传完毕");
    }
}

interface ILog
{
    public void Log(string message);
}

class LogImpl : ILog
{
    public void Log(string message)
    {
        Console.WriteLine($"日志为{message}");
    }
}

interface IConfig
{
    public string GetValue(string name);
}

class ConfigImpl : IConfig
{
    public string GetValue(string name)
    {
        return "hello";
    }
}

class DBConfigImpl : IConfig
{
    public string GetValue(string name)
    {
        Console.WriteLine("从数据库读取的配置");
        return "from db";
    }
}

interface IStorage
{
    public void Save(string content, string name);
}

class StorageImpl : IStorage
{
    private readonly IConfig config;
    public StorageImpl(IConfig config)
    {
        this.config = config;
    }
    public void Save(string content, string name)
    {
        string server = config.GetValue("server");
        Console.WriteLine($"向服务器{server}的文件名为{name}上传{content}");
    }
}

}

```

运行结果

image.png

相关优化

修改DependencyInjection类

相关代码

``` using ConfigServices; using LogServices; using MailServices; using Microsoft.Extensions.DependencyInjection;

namespace MailSender { class Program { static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection();

serviceCollection.AddScoped<IConfigService, EnvVarConfigService>();
        serviceCollection.AddLayeredConfig();


        serviceCollection.AddConsoleLog();

        /* serviceCollection.AddScoped(
             typeof(IConfigService),
             s =>
                 new IniFileConfigService
                 {
                     FilePath = "mail.ini"
                 });*/
        serviceCollection.AddIniFileConfig("mail.ini");

       /* serviceCollection.AddScoped<IConfigService, EnvVarConfig>();*/
        serviceCollection.AddScoped<IMailService, MailService>();
      /*  serviceCollection.AddScoped<ILogProvider, ConsoleLogProvider>();*/

        using (var sp = serviceCollection.BuildServiceProvider())
        {
            // 第一个根上的对象只能用ServiceLocator
            var mailService = sp.GetRequiredService<IMailService>();
            mailService.Send("Hello", "to@123.com", "content");
        }

        Console.Read();
    }
}

} ```

重点代码块

serviceCollection.AddScoped( typeof(IConfigService), s => new IniFileConfigService { FilePath = "mail.ini" });

修改后

serviceCollection.AddIniFileConfig("mail.ini"); DependencyInjection 命名空间下,新增了AddIniFileConfig方法,使用时候只需要传入配置文件信息即可

``` using ConfigServices; using MailSender; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection { public static class IniFileConfigExtensions { public static void AddIniFileConfig(this IServiceCollection services,string filePath) { services.AddScoped( typeof(IConfigService), s => new IniFileConfigService { FilePath = filePath }); }

}

}

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值