没有 ASP.NET Core 的 .NET Core 中的 DI [英] DI in .NET Core without ASP.NET Core

查看:24
本文介绍了没有 ASP.NET Core 的 .NET Core 中的 DI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 .NET Core 编写一个守护进程,它基本上就像一个 cron 作业,只是在某个时间间隔内编排 API/DB 调用.因此,它不需要公开任何 Web 路由,因此不需要 ASP.NET Core.

I'm looking to write a daemon process using .NET Core which will basically act much like a cron job and just orchestrate API/DB calls on some interval. As such, it has no need to expose any web routes, so there's no need for ASP.NET Core.

但是,您可以通过 afaik ASP.NET Core 获得出色的 Startup 类,其中包含您可能需要的所有 DI 管道和基于环境的配置.

However, afaik ASP.NET Core is where you get that nice Startup class with all the DI plumbing and environment-based configuration you might need.

在我看来,我有两个选择:

The way I see it, I have two options:

  1. 放弃 ASP.NET Core 并自行连接 DI 框架.如果我走那条路,我该怎么做?
  2. 只为 DI 部分包含 ASP.NET Core,但是我如何生成在任何请求上下文之外永远运行"的后台任务?我的理解是,DI 框架非常假设存在某种传入请求来协调所有注入.

推荐答案

从 .NET Core 2.1 开始,这可以/应该使用通用主机来完成.从.NET 核心文档:

As of.NET Core 2.1 this can/should be done with a Generic Host. From .NET Core docs:

通用主机的目标是将 HTTP 管道与 Web 主机 API 分离,以支持更广泛的主机场景......"

"The goal of the Generic Host is to decouple the HTTP pipeline from the Web Host API to enable a wider array of host scenarios..."

https:///docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1

public static async Task Main(string[] args)
{
  var builder = new HostBuilder()
    .ConfigureAppConfiguration((hostingContext, config) =>

    .ConfigureServices((hostContext, services) =>
    {
       // ...
    });

  await builder.RunConsoleAsync();
}

这篇关于没有 ASP.NET Core 的 .NET Core 中的 DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆