.NET使用依赖注入,控制反转

30 篇文章 1 订阅

.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。作者:xxx
    public 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("新增失败");
        }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值