一,最初的依赖注入
- 首先定义User类
public record User(long Id,string UserName,string Password);
- 然后是两个接口
public interface IUserDAO
{
//查询用户名为userName的用户信息
public User GetByUserName(string userName);
}
public interface IUserBiz
{
//检查用户名、密码是否正确
public bool CheckLogin(string username, string password);
}
- 两个实现类
public class UserBiz : IUserBiz
{
private readonly IUserDAO userDao;
public UserBiz(IUserDAO userDao)
{
this.userDao = userDao;
}
public bool CheckLogin(string username, string password)
{
var user = userDao.GetByUserName(username);
if(user == null)
{
return false;
}
else return user.Password == password;
}
}
class UserDAO : IUserDAO
{
private readonly IDbConnection conn;
public UserDAO(IDbConnection conn)
{
this.conn = conn;
}
public User? GetByUserName(string userName)
{
using var dt = SqlHelper.ExecuteQuery(conn,$"select * from T_Users where UserName={userName}");
if(dt.Rows.Count <= 0)
{
return null;
}
DataRow row = dt.Rows[0];
long id = (long)row["id"];
string uname = (string)row["UserName"];
string password = (string)row["Password"];
return new User(id,uname,password);
}
}
- 最后是创建
ServiceCollection
对象,然后进行服务注册,最后调用BuildServiceProvider
方法来生成IServiceCollection
对象
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddScoped<IDbConnection>(sp =>
{
string connStr = "Data Source=.;Initial Catalog=DI_DB;Integrated Security=true";
var conn = new SqlConnection(connStr);
conn.Open();
return conn;
});
services.AddScoped<IUserDAO,UserDAO>();
services.AddScoped<IUserBiz,UserBiz>();
using (ServiceProvider sp = services.BuildServiceProvider())
{
var userBiz = sp.GetRequiredService<IUserBiz>();
bool b = userBiz.CheckLogin("zhm", "123456");
Console.WriteLine(b);
}
}
二,ASP.NET Core的依赖注入
我们创建了ASP.NET Core的项目后,打开Program.cs
文件,我们可以看到WebApplication.CreateBuilder(args)
方法返回的是WebApplicationBuilder
类型的对象,而WebApplicationBuilder
类型中的 Services 属性就是类型为IServiceCollection
的属性,我们一般把服务注册到这个Services属性中即可
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
- ASP.NETCore初始项目模板中,我们通过调用AddControllers方法把项目中的控制器及相关的服务注册到容器中,然后通过调用AddSwaggerGen方法把 Swagger相关的服务注册到容器中。
- 当我们需要注册服务的时候,只要把注册代码写到Program.cs的builder.Build之前即可。一般来讲,服务的注册顺序不会影响程序的运行效果,因此我们一般不用关注不同服务注册代码的顺序。
由于控制器是被AddControllers方法注册到容器中的,而且控制器的实例化是由依赖注入框架来负责的,因此在控制器中我们同样可以用依赖注入的方式来使用容器中的服务
演示
public class MyService1
{
public IEnumerable<string> GetNames()
{
return new string[] { "Tom","Zack","Jack"};
}
}
- 接下来,我们在ASP.NET Core 项目的Program.cs文件中的 var app=builder.Build()代码之前注册MyServicel服务
builder.Services.AddScoped<MyService1>();
- 接下来,在控制器中,我们就可以通过构造方法来注入服务了
public class TestController : ControllerBase
{
private readonly MyServicel myServicel;
public TestController(MyServicel myServicel)
{
this.myServicel=myServicel;
}
[HttpGet]
public string Test()
{
var names= myServicel.GetNames();
return string.Join(",",names);
}
}