我在一个全新的.net core 2 Web应用程序中发生了一件奇怪的事情。这是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
实现IHostedService
和IDisposable
。
services.AddHostedService<MainLoop>();
无法解决,产生了所有爵士乐,出现错误“'IServiceCollection'不包含'AddHostedService'的定义,也没有扩展方法...”。我检查了Microsoft.Extensions.DependencyInjection
的来源,并且清楚地看到了public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
如果没有托管服务引用,则项目可以正常编译。有什么我想念的吗?
答案 0 :(得分:7)
AddHostedService
是Microsoft.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;
}
}
}
并确保已安装并引用了相关的软件包以访问扩展方法