Ядро asp.net AppSettings не работает, когда используется внутри размещенного сервиса - PullRequest
2 голосов
/ 14 мая 2019

У меня есть следующее:

   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 также используется внутри другого сервиса.Когда я удаляю AppSettings из HostedService, он работает.

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)

Что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 14 мая 2019

Скорее всего, Autofac не настроен или не отображается в правильном месте.

Ошибка сообщает, что Autofac не может найти класс Test.MicroService.MicroServices.Infrastructure.AppSettings, даже если есть вызов

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

Этот вызов зарегистрирует класс AppSettings в текущем DI-контейнере. Это означает, что контейнер DI должен быть настроен до любой попытки регистрации служб.

var host = new WebHostBuilder()
    .UseKestrel()
    .ConfigureServices(services => services.AddAutofac())
    ....
    .UseStartup<Startup>()
    .Build();
0 голосов
/ 14 мая 2019

Хост-сервисы работают в отдельном потоке. 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>();

}
...