我有以下内容:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services => services.AddAutofac());
public class HostedServiceA : IHostedService
{
private readonly AppSettings appSettings;
public HostedServiceA(AppSettings appSettings)
{
this.appSettings = appSettings;
}
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddHttpClient();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddHostedService<HostedServiceA>();
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<SomeService>().As<ISomeService>().SingleInstance();
}
我正在使用autofac。当我尝试运行时,出现异常,程序无法启动:AppSettings也用于另一个服务中。当我从HostedService删除AppSettings时,它会起作用。
Unhandled Exception: Autofac.Core.DependencyResolutionException: An exception was thrown while activating Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor -> ?:Microsoft.Extensions.Hosting.IHostedService[] -> Test.MicroService.MicroServices.Web.HostedServices.RatesHostedService. ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Test.MicroService.MicroServices.Web.HostedServices.RatesHostedService' can be invoked with the available services and parameters:
Cannot resolve parameter 'Test.MicroService.MicroServices.Infrastructure.AppSettings appSettings' of constructor 'Void .ctor(Test.MicroService.MicroServices.Infrastructure.AppSettings)'. at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Reflection\ReflectionActivator.cs:line 160
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Reflection\ReflectionActivator.cs:line 120
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 118
--- End of inner exception stack trace ---
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 136
at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator) in C:\projects\autofac\src\Autofac\Core\Lifetime\LifetimeScope.cs:line 306
at Autofac.Core.Resolving.InstanceLookup.Execute() in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 85
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 130 at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 83
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 1041
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 871
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
我在做什么错了?
答案 0 :(得分:0)
托管服务在单独的线程上运行。 DI按线程工作,您将需要执行以下操作:
public MyHostedService(IServiceScopeFactory serviceScopeFactory)
: base(consumer)
{
_serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
}
And inside the method use like this:
using (var scope = _serviceScopeFactory.CreateScope())
{
var storageService = scope.ServiceProvider.GetRequiredService<MyService>();
}
答案 1 :(得分:0)
很可能没有配置Autofac,或者配置没有出现在正确的位置。
该错误抱怨即使有
的调用,Autofac也无法找到Test.MicroService.MicroServices.Infrastructure.AppSettings
类
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
此调用将向当前的DI容器注册AppSettings
类。这意味着必须在尝试注册服务之前 配置DI容器。
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
....
.UseStartup<Startup>()
.Build();