带ASP.Net Core 2.0 IOptionsSnapshot注入的简单注入器

时间:2018-08-19 18:09:50

标签: c# asp.net-core-2.0 simple-injector

我正在尝试在错误#429中提出的建议,但得到的错误与他在此报告的错误相同,但后来却没有提供堆栈跟踪信息。我还阅读并使用了直到最近为止您不使用IOptions和相关类的指南。当我们在Azure中运行某些东西时,我们确实需要IOptionsSnapshot,并需要能够在达到极限时即时打开/关闭选项,并且重启服务不是一种选择。由于我们需要一些第三方产品,因此最初需要5分钟以上的时间才能开始。

这是我们设置的:

  • 简单注入器4.3.0
  • .NET Core 2.0 Web API

界面ISearchSettings->类SearchSettings
(基本上,这里的所有属性,除了1个布尔值,我们都可以根据需要进行单例化。一个布尔值有点告诉我们是使用内部搜索还是使用天蓝色搜索)

应用启动时,出现以下错误:

  

System.InvalidOperationException:配置无效。创建类型为IOptionsSnapshot 的实例失败。类型为IOptionsSnapshot 的注册委托引发了异常。无法从ASP.NET Core请求服务请求服务'IOptionsSnapshot 。请确保在活动HTTP请求的上下文中调用此方法。

在配置服务中:

services.AddOptions();  
services.Configure<ISearchSettings>(
    this.Configuration.GetSection("AzureSearchSettings"));  
services.Configure<SearchSettings>(
    this.Configuration.GetSection("AzureSearchSettings"));  
// The next line was added trying some other suggestions from similar
// errors. It didn't resolve the issue  
services.AddScoped(
    cfg => cfg.GetService<IOptionsSnapshot<SearchSettings>>().Value);  
...  
services.AddMvc();  
...  
IntegrateSimpleInjector();  

在IntegrateSimpleInjector中:

this.container.Options.DefaultScopedLifestyle =
    new AsyncScopedLifestyle();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IControllerActivator>(
    new SimpleInjectorControllerActivator(this.container));
services.AddSingleton<IViewComponentActivator>(
    new SimpleInjectorViewComponentActivator(this.container));

services.EnableSimpleInjectorCrossWiring(this.container);
services.UseSimpleInjectorAspNetRequestScoping(this.container);

在InitializeContainer中:

// I have tried both Lifestyle Transient and Scoped
this.container.Register<IOptionsSnapshot<SearchSettings>>(
    () => app.GetRequestService<IOptionsSnapshot<SearchSettings>>(),
    Lifestyle.Transient);
...
this.container.AutoCrossWireAspNetComponents(app);

Stacktrace:

at SimpleInjector.SimpleInjectorAspNetCoreIntegrationExtensions.GetRequestServiceProvider(IApplicationBuilder builder, Type serviceType)
at SimpleInjector.SimpleInjectorAspNetCoreIntegrationExtensions.GetRequestService[T](IApplicationBuilder builder)
at QuotingService.Startup.<>c__DisplayClass9_0.<InitializeContainer>b__0() in E:\Repos\QuotingService\QuotingService\Startup.cs:line 299
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance()
at SimpleInjector.InstanceProducer.GetInstance()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
at SimpleInjector.Container.VerifyInstanceCreation(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyInternal(Boolean suppressLifestyleMismatchVerification)
at SimpleInjector.Container.Verify()
at QuotingService.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) in E:\Repos\QuotingService\QuotingService\Startup.cs:line 229
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

要使此功能生效,有什么需要改变的想法吗?
感谢您提供的出色产品以及所提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

您应该避免在简单的Injector注册的委托中调用GetRequestService,因为这种调用需要存在一个活动的HTTP请求,该请求在应用程序启动期间将不可用。

相反,请依靠AutoCrossWireAspNetComponents从ASP.NET Core中获取IOptionsSnapshot<SearchSettings>

但是,要使其正常工作,您需要致电services.Configure<SearchSettings>

这是有效的配置:

public class Startup
{
    private Container container = new Container();

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");
        this.Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // ASP.NET default stuff here
        services.AddMvc();

        this.IntegrateSimpleInjector(services);

        services.Configure<SearchSettings>(
            Configuration.GetSection("SearchSettings"));
    }

    private void IntegrateSimpleInjector(IServiceCollection services)
    {
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddSingleton<IControllerActivator>(
            new SimpleInjectorControllerActivator(container));

        services.EnableSimpleInjectorCrossWiring(container);
        services.UseSimpleInjectorAspNetRequestScoping(container);
    }

    public void Configure(IApplicationBuilder app)
    {
        container.AutoCrossWireAspNetComponents(app);
        container.RegisterMvcControllers(app);

        container.Verify();

        // ASP.NET default stuff here
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

使用此配置,您可以在任何地方注入IOptionsSnapshot<T>。例如在您的HomeController内:

public class HomeController : Controller
{
    private readonly IOptionsSnapshot<SearchSettings> snapshot;

    public HomeController(
        IOptionsSnapshot<SearchSettings> snapshot)
    {
        this.snapshot = snapshot;
    }
}