1. 程式人生 > 實用技巧 >net core 單例注入,專案啟動時呼叫

net core 單例注入,專案啟動時呼叫

Startup檔案

IServiceProvider通過GetService(Type serviceType)拿到例項

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<TestServer>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) {
if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); TestServer testServer = serviceProvider.GetService<TestServer>(); testServer.Start(); } }
public class TestServer
{
    private readonly IHostingEnvironment _iHostingEnvironment;

    public TestServer(IHostingEnvironment iHostingEnvironment)
    {
        _iHostingEnvironment = iHostingEnvironment;
    }

    public void Start()
    {

        Console.WriteLine(_iHostingEnvironment.WebRootPath);
    }
}