分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

.NET Core ConfigureServices

发布时间:2023-09-06 01:43责任编辑:苏小强关键词:.NET

节选自这里

ConfigureServices是Startup类中可以选择定义的一个方法,作用即实现了依赖注入(DI)的配置,只有把服务添加到服务容器中才能让这些服务可以通过依赖注入的形式在应用中使用。方法参数如下:

  • IServiceCollection:整个ASP.NET Core 默认带有依赖注入(DI),IServiceCollection是依赖注入的容器,首先创建一个类(Foo)和接口(IFoo),代码清单如下:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace WebApplication1{ ??public interface IFoo ???{ ???????string GetFoo(); ???}}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace WebApplication1{ ???public class Foo : IFoo ???{ ???????public string GetFoo() ???????{ ???????????return "foo"; ???????} ???}}

在ConfigureServices 中将接口和实现注入至容器

public void ConfigureServices(IServiceCollection services){ ???services.AddTransient<IFoo, Foo>();}

如果想在每次Http请求后都使用IFoo的GetFoo()方法来处理,上面讲到可以在Configure方法中注册函数,在注册过程中由于使用了依赖注入(DI),因此可以直接通过 RequestServices.GetRequiredService<IFoo>() 泛型方法将IFoo对象在容器中取出。

app.Run((context) =>{ ??????var str = context.RequestServices.GetRequiredService<IFoo>().GetFoo(); ??????return context.Response.WriteAsync(str);});

除了自己的接口外,还支持通过扩展方法添加更多的注入方法,比如EntityFramework、mvc框架都实现自己的添加方法。

public void ConfigureServices(IServiceCollection services){ ???// Add framework services. ???services.AddDbContext<ApplicationDbContext>(options => ???????options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); ???services.AddIdentity<ApplicationUser, IdentityRole>() ???????.AddEntityFrameworkStores<ApplicationDbContext>() ???????.AddDefaultTokenProviders(); ???services.AddMvc(); ???// Add application services. ????services.AddTransient<IFoo, Foo>();}

.NET Core ConfigureServices

原文地址:https://www.cnblogs.com/shuangzimuchangzhu/p/8458296.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved