本文主要是介绍ASP.NET Core获取已经在Startup.cs中注册的服务实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
新版本.NET5参考代码
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebNetCore5_Img_Storage.BLL;
using WebNetCore5_Img_Storage.IBLL;
using WebNetCore5_Img_Storage.Model.Tool;namespace WebNetCore5_Img_Storage
{public class Program{public static void Main(string[] args){ //可以吧IHost设置为公共的静态变量,存放起来,其他地方也可以调用 //CreateHostBuilder(args).Build().Run();IHost host = CreateHostBuilder(args).Build();//从容器中获取已经注册的IUploadFileRecordBLL//先读取最近上传图片缓存起来,1000条,方便快速预览图片,减小延迟IUploadFileRecordBLL uploadFileRecordBLL = (IUploadFileRecordBLL)host.Services.GetService(typeof(IUploadFileRecordBLL));var task = uploadFileRecordBLL.PageAsync(new Model.Upload_file_record() { Buncket = minio_img_bucket }, 1, 1000);task.Wait();var page = task.Result;if (page.Total > 0){foreach (var item in page.List){Task.Run(async () =>{ //图片预览地址string imgURL =await MinioHandle.GetImgSignedUrl(item.Server_port,item.Buncket, item.File_name);System.Net.WebClient webClient = new System.Net.WebClient();byte[] buffe = await webClient.DownloadDataTaskAsync(imgURL);System.Runtime.Caching.MemoryCache.Default.Set("Orig"+item.Id, buffe, DateTime.UtcNow.AddDays(7));LogHelpter.AddLog("程序启动生成的图片原生字节缓存 "+ item.Id);});}}//启动网站host.Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{//webBuilder.Limits.MinResponseDataRate = null;//webBuilder.UseIIS().UseStartup<Startup>();webBuilder.UseStartup<Startup>();});}
}
老版本.NET Core3
//Startup.cs中IServiceProvider
public void ConfigureServices(IServiceCollection services)
{string sqlConnection = "连接字符串"; services.AddDbContext<DataContext>(option => option.UseSqlServer(sqlConnection));services.AddScoped<IGroupChartsRepository, GroupChartsRepository>();services.AddScoped<ICombinationGroupChartsRepository, CombinationGroupChartsRepository>();services.AddScoped<ILogRepository, LogRepository>();
}//获取已经注册的实例,比如在public class ExceptionFilter : IExceptionFilter这个类中获取
IWebHost host = Program.BuildWebHost(null);
IServiceScope scope = host.Services.CreateScope();
ILogRepository _logRepository = scope.ServiceProvider.GetService<ILogRepository>();
DataContext _dataContext = scope.ServiceProvider.GetService<DataContext>();
//处理业务逻辑,比如新增记录
Log log = new Log();
_logRepository.Add(log);
string dateTime = DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd");
int count = _dataContext.Database.ExecuteSqlCommand("delete from Log where CONVERT(varchar(30), CreateTime, 23)<@date", new SqlParameter("date", dateTime));scope.Dispose();
这篇关于ASP.NET Core获取已经在Startup.cs中注册的服务实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!