.NET 6-注入服务中的program.cs
我知道如何在.net 5(或之前)中的启动con中进行依赖注入,但是我如何使用.NET 6中的top级program.cs进行同样的操作?
.NET 5:例如,我可以在配置方法中注入一类,
public class Startup
{
public IConfiguration _configuration { get; }
public IWebHostEnvironment _env { get; set; }
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
_configuration = configuration;
_env = env;
}
public void ConfigureServices(IServiceCollection services)
{
// TODO
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IToInjectService serviceToInject)
{
// USE SERVICE
}
}
如何在.NET 6中实现这一目标?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用.NET 6很容易。只需在配置应用程序服务后执行getService方法,并已运行构建方法。
Using .Net 6 is easy. Just execute GetService method after configure app services and have ran Build method.
如果您需要在开始时使用范围的服务,这就是您的 program.cs 应该看起来像:
从:
在应用程序启动上解决服务
它确实适用于mi dbinitializer
If you need to use a scoped service at start, this is how your program.cs should looks like:
from:
Resolve a service at app start up
it did work for mi DbInitializer
您将服务添加到
builder.Services
集合,然后使用You add your service to the
builder.Services
collection and then access it with在
program.cs
文件中,您可以通过Builder.Services
来管理您的
服务
Inside the
program.cs
file you can manage your services bybuilder.Services
For example, I added DbContext and Two different services based on the Singleton pattern and Scoped
For more information check Code samples migrated to the new minimal hosting model in ASP.NET Core 6.0
我尝试使用
getService
方法,但我将服务接口类型作为输入(如下所示)传递给我,这与我一起使用。I tried to use the
GetService
method but I pass the service interface type as input (as shown below) and this worked with me.