.NET使用依赖注入,控制反转
.NET 支持依赖项注入 (DI) 软件设计模式,这是一种在类及其依赖项之间实现 控制 (IoC) 的反转 的技术
在设计能够进行依赖注入的服务时:
- 避免有状态的、静态类和成员。 通过将应用设计为改用单一实例服务,避免创建全局状态。
- 避免在服务中直接实例化依赖类。 直接实例化会将代码耦合到特定实现。
- 不在服务中包含过多内容,确保设计规范,并易于测试。
如果一个类有很多已注入的依赖关系,这可能表明该类拥有过多的责任,并且违反了单一责任原则 (SRP)。 尝试通过将某些职责移动到一个新类来重构类。
使用的包Microsoft.Extensions.DependencyInjection
参考微软文档
.NET 依赖项注入
https://learn.microsoft.com/zh-cn/dotnet/core/extensions/dependency-injection
使用依赖关系注入
https://learn.microsoft.com/zh-cn/dotnet/core/extensions/dependency-injection-usage
依赖关系注入指南
https://learn.microsoft.com/zh-cn/dotnet/core/extensions/dependency-injection-guidelines
Program.cs
using WzfgsInfoReportNET6.IBLL;
using WzfgsInfoReportNET6.IBLL_impl;
using WzfgsInfoReportNET6.IDao;
using WzfgsInfoReportNET6.IDao_impl;
using WzfgsInfoReportNET6.Models;var builder = WebApplication.CreateBuilder(args);#region 业务层接口,实现注册builder.Services.AddSingleton<IAnMenusBll, AnMenusBll>();
builder.Services.AddSingleton<IAnRoleBll, AnRoleBll>();
builder.Services.AddSingleton<IAnUserBll, AnUserBll>();
builder.Services.AddSingleton<IArticle2Bll, Article2Bll>();#endregion#region 数据层接口,实现注册builder.Services.AddSingleton<IAdoptedRecordDao, AdoptedRecordDao>();
builder.Services.AddSingleton<IAnMenusDao, AnMenusDao>();
builder.Services.AddSingleton<IAnRoleDao, AnRoleDao>(); #endregion// Add services to the container.
builder.Services.AddControllersWithViews();var app = builder.Build();
AppHelpter.App = app;//var kkk = app.Services.GetRequiredService<IAnMenusDao>();
//var bbb = WebApplicationBuilderHelpter.GetServices<ITaskBll>();// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();
工具类,获取注册的实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;namespace WzfgsInfoReportNET6.Models
{/// <summary>/// 依赖注册,获取接口实例/// </summary>/// 创建时间:2023-4-11 16:48:42。作者:xxxpublic sealed class AppHelpter{/// <summary>/// 程序/// </summary>public static WebApplication App { get; set; }/// <summary>/// 获取接口实例/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static T GetServices<T>() where T : notnull{T instance = App.Services.GetRequiredService<T>();return instance;}}
}
调用
public class AnRoleBll : IAnRoleBll
{readonly IAnRoleDao anRoleDao= AppHelpter.GetServices<IAnRoleDao>();readonly IAnUserDao anUserDao= AppHelpter.GetServices<IAnUserDao>();readonly IRoleFunctionsDao roleFunctionsDao = AppHelpter.GetServices<IRoleFunctionsDao>();public async Task<Result> AddAsync(AnRole model){ int count = await anRoleDao.AddAsync(model);if (count > 0){return new Result(true);}return new Result("新增失败");}
}