我在一个全新的.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"}
);
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
MainLoop
实施IHostedService
和IDisposable
.
该services.AddHostedService<MainLoop>();
不能解决,产生错误"'IServiceCollection’不包含'AddHostedService’,没有扩展方法的定义......"所有的爵士乐.我检查了Microsoft.Extensions.DependencyInjection
源代码,我清楚地看到了定义public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
没有托管服务引用,项目编译就好了.有什么我想念的吗?
AddHostedService
是的一部分Microsoft.Extensions.Hosting.Abstractions
.
虽然它是在定义的Microsoft.Extensions.DependencyInjection
命名空间,它属于 Microsoft.Extensions.Hosting.Abstractions
在ServiceCollectionHostedServiceExtensions
类
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并确保安装和引用相关软件包以访问扩展方法
归档时间: |
|
查看次数: |
1907 次 |
最近记录: |