分享web开发知识

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

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

Asp.net core 学习笔记 ( DI 依赖注入 )

发布时间:2023-09-06 01:20责任编辑:苏小强关键词:暂无标签

比起 Angular 的依赖注入, core 的相对简单许多, 容易明白 

所有 provider 都在 startup 里配置. 

public void ConfigureServices(IServiceCollection services){ ???services.Configure<Business>(Configuration.GetSection("business")); ???services.Configure<Configuration.Email>(Configuration.GetSection("email")); ???services.AddEmail(); ???// Razor template ????services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>(); ???services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); ???// Entity ????services.AddScoped(_ => new DB(Configuration.GetConnectionString("DefaultConnection"))); ???// hangfire ???services.AddHangfire(config => ???????????config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"))); ???// MVC ???services.Configure<RazorViewEngineOptions>(options => ???{ ???????options.ViewLocationExpanders.Add(new FeatureLocationExpander()); ???}); ???services.AddMvc();}

controller 就通过 constructor 来注入就可以了. 

private readonly DB db;private ICompositeViewEngine CompositeViewEngine { get; set; }private ActionContext ActionContext { get; set; }private IServiceProvider ServiceProvider { get; set; }private ITempDataProvider TempDataProvider { get; set; }private Configuration.Email EmailConfig { get; set; }public DebugController( ???DB db, ???ICompositeViewEngine compositeViewEngine, ???IActionContextAccessor actionContextAccessor, ???IServiceProvider serviceProvider, ???ITempDataProvider tempDataProvider, ???IOptionsSnapshot<Configuration.Email> emailOptionsAccessor){ ???CompositeViewEngine = compositeViewEngine; ???ActionContext = actionContextAccessor.ActionContext; ???ServiceProvider = serviceProvider; ???TempDataProvider = tempDataProvider; ???EmailConfig = emailOptionsAccessor.Value; ???this.db = db;}

provider 有 3 个级别 

AddSingleton

AddScoped

AddTransient

单列是说整个 App 用一个实例

Scope 一个 request 一个实例

transient 则是每一个注入一个实例

一个模块一般上会提供好多 Service 

那么要让 startup 干净一些的话,我们可以包装起来 

就好像这样  services.AddEmail();

做法是开一个扩展方法 

namespace Project.Email{ ???public static class ServiceCollectionExtensions ???{ ???????public static IServiceCollection AddEmail( ???????????this IServiceCollection services) ???????{ ???????????services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>(); ???????????services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); ???????????services.AddScoped<EmailService, EmailService>(); ???????????return services; ???????} ???} ???public class EmailService ???{ ???????public EmailService() ???????{ ???????} ???????public string name { get; set; } = "dada"; ???}}

Asp.net core 学习笔记 ( DI 依赖注入 )

原文地址:http://www.cnblogs.com/keatkeat/p/7742543.html

知识推荐

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