一个例子 依赖注入只需要修改注入, 就能改变实现
using Microsoft.Extensions.DependencyInjection;
using System;
namespace DependencyInjectionDemon2
{
class Program
{
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddScoped<Controller>();
services.AddScoped<ILog, LogImpl>();
services.AddScoped<IStorage, StorageImp1>();
//services.AddScoped<IConfig, DBConfigImp1>();
services.AddScoped<IConfig, ConfigImp1>();
//注册服务放在BuildServiceProvider之前
using (var sp = services.BuildServiceProvider())
{
var a = sp.GetRequiredService<Controller>();
a.Test();
}
}
//日志:开始上传
//向服务器从数据库读取配置的文件名1.txt上传sasasaddfds
//日志:上传完毕
//注释掉 DBConfigImp1
//日志:开始上传
//向服务器从本地文本读入配置的文件名1.txt上传sasasaddfds
//日志:上传完毕
//依赖注入只需要修改注入, 就能改变实现
}
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("开始上传"); //字符串参数
storage.Save("sasasaddfds", "1.txt");
log.Log("上传完毕");
}
}
interface ILog

本文通过示例介绍了依赖注入的概念及其实现方式,展示了如何通过修改注入的服务来改变应用程序的行为,并探讨了瞬态、单例和范围服务的区别。
最低0.47元/天 解锁文章
1056

被折叠的 条评论
为什么被折叠?



