排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

添加注入
首先需要添加好一个注入:
其实添加好类与类之间的关系,在ConfigureServices中添加注入
services.AddTransient<IArticleDAL, ArticleDAL>();
获取注入的方式
构造函数注入:
private IArticleDAL _articleDAL; public ArticleController(IArticleDAL articleDAL) { _articleDAL = articleDAL; }
使用FromServices获取
public async Task<List<Persons>> ElasticTest([FromServices] IElasticSearchServer elasticSearchServer) { var list = await elasticSearchServer.ElasticLinqClient.SearchAsync<Persons>( p => p.Index("users") .Query(op => op.Match( ss => ss.Field( qq => qq.user == "xj")))); return list.Documents.ToList(); }
直接获取
直接通过 HttpContext来获取实例
HttpContext下有一个RequestedService同样可以用来获取实例对象,不过这种方法一般不很推荐。
IUserDAL userDAL = HttpContext.RequestServices.GetService(typeof(IUserDAL)) as IUserDAL;
属性注入:
ASP.NET Core 的标准依赖注入容器不支持属性注入。但是你可以使用其他容器支持属性注入
在view中使用
在View中需要用@inject ,起一个别名。
@using AJ.Services; @model AJ.Models.AccountViewModel.LoginViewModel @inject ILoginService<ApplicationUser> userService <!DOCTYPE html> <html > <head></head> <body> @userService.GetUserName() </body> </html>
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价