.NetCore之依赖注入

先上一段官方文档概括一下依赖注入的实现

  • 使用接口或基类将依赖关系实现抽象化。
  • 在服务容器中注册依赖关系。 ASP.NET Core 提供了一个内置的服务容器 IServiceProvider。 服务通常已在应用的 Program.cs 文件中注册。
  • 将服务注入到使用它的类的构造函数中。 框架负责创建依赖关系的实例,并在不再需要时将其释放。

个人理解:

类A依赖类B,在行为上是在类A中需要实例化(new)类B来使用它的内容。这一段关系称为依赖关系。那么实现依赖注入就是:实现类继承服务类(接口),并实现它的方法将它注册到容器中,在通过构造函数注入,由容器来实例化并管理(生命周期)。

仅供参考,官网原文为主

上手操作:

创建一个接口

namespace demo.Services
{
    public interface IStudent
    {
        public void write(string a);
    }
}

创建一个类继承接口

using demo.Services;

namespace demo.DAL
{
    public class Student : IStudent
    {
        public void write(string b)
        {
            Console.WriteLine($"MyDependency.WriteMessage Message: {b}");
        }
    }
}

在program文件中注册到容器

using demo.DAL;
using demo.Services;
namespace demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            
            // Add services to the container.
            builder.Services.AddRazorPages();

            //这里使用了一个生命周期Scoped为范围内,生命周期解释参考原文

            //应该有其他注册到容器的方法,还没学会。

            //个人问题,如果有很多类和对应的接口,难道要每个注册一次?
            builder.Services.AddScoped<IStudent, Student>();
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapRazorPages();
            app.Run();
        }
    }
}

通过构造函数注入

public class IndexModel : PageModel
    {
        public string str { get; set; }
        private readonly ILogger<IndexModel> _logger;
        private readonly IStudent _student;
        public IndexModel(ILogger<IndexModel> logger, IStudent student)
        {
            _logger = logger;
            _student = student;
        }

        public void OnGet()
        {
            _student.write("这是打印数据");
        }
    }

  • 15
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值