发布时间:2023-08-29 15:15:37来源:本站阅读(1087)
1、新建.NET6 WEB项目
2、新建IDatabase接口
public interface IDatabase
{
public void Insert();
public void Update();
}
3、写2个实现
public class MysqlDataBase : IDatabase
{
public void Insert()
{
Console.WriteLine("MysqlDataBase插入");
}
public void Update()
{
Console.WriteLine("MysqlDataBase更新");
}
}
public class SqlServerDataBase : IDatabase
{
public void Insert()
{
Console.WriteLine("SqlServerDataBase插入");
}
public void Update()
{
Console.WriteLine("SqlServerDataBase更新");
}
}
4、注入
builder.Services.AddScoped();
builder.Services.AddScoped();
5、使用
public class HomeController : ControllerBase
{
private readonly IEnumerable databases;
public HomeController(IEnumerable databases)
{
this.databases = databases;
}
public string Get()
{
var s1 = databases.Where(c => c.GetType() == typeof(MysqlDataBase)).FirstOrDefault();
var s2 = databases.Where(c => c.GetType() == typeof(SqlServerDataBase)).FirstOrDefault();
s1?.Insert();
s2?.Insert();
return "success";
}
}
关键字:
上一篇: C#使用时间戳
下一篇: 十大编程算法助程序员走上高手之路
1752
1553
2048
1509
915
1420
1436
940
792
1939
9593
5996
5523
5116
4567
4274
3415
3336
3335
3269