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();
                    webBuilder.UseStartup<Startup>();
                });
    }
}

老版本.NET Core3

//Startup.cs中IServiceProvider
public void ConfigureServices(IServiceCollection services)
{
	string sqlConnection = "连接字符串";	 
	services.AddDbContext(option => option.UseSqlServer(sqlConnection));
	 
	services.AddScoped();
	services.AddScoped();
	services.AddScoped();
}

//获取已经注册的实例,比如在public class ExceptionFilter : IExceptionFilter这个类中获取
IWebHost host = Program.BuildWebHost(null);                   
IServiceScope scope = host.Services.CreateScope();
ILogRepository _logRepository = scope.ServiceProvider.GetService();
DataContext _dataContext = scope.ServiceProvider.GetService();
//处理业务逻辑,比如新增记录
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();

你可能感兴趣的:(EF,Core,asp.net,core,.NET,Core,.net,core,获取已经注册的实例)