gpt4 book ai didi

c# - IServiceCollection.AddHostedService<>();没有解决

转载 作者:太空狗 更新时间:2023-10-30 00:37:27 26 4
gpt4 key购买 nike

我在全新的 .net core 2 网络应用程序中发生了一件奇怪的事情。这是来自 Visual Studio 内置模板的标准 Web API。 VS 2017,所有的爵士乐。这是整个 startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using VerySimpleAPI.Helpers;

namespace VerySimpleAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddHostedService<MainLoop>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc(routes => {
routes.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index"}
);
});
}
}
}

MainLoop工具 IHostedServiceIDisposable .

services.AddHostedService<MainLoop>();没有解决,产生错误“‘IServiceCollection’不包含‘AddHostedService’的定义,也没有扩展方法……”所有这些爵士乐。我检查了 Microsoft.Extensions.DependencyInjection来源,我清楚地看到 public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services) 的定义

没有托管服务引用,项目编译得很好。有什么我想念的吗?

最佳答案

AddHostedServiceMicrosoft.Extensions.Hosting.Abstractions 的一部分。

虽然它是在 Microsoft.Extensions.DependencyInjection 命名空间中定义的,但它属于 ServiceCollectionHostedServiceExtensions 中的 Microsoft.Extensions.Hosting.Abstractions

using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;

namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionHostedServiceExtensions
{
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, THostedService>());

return services;
}
}
}

并确保安装和引用了相关包以访问扩展方法

关于c# - IServiceCollection.AddHostedService<>();没有解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com