代码之家  ›  专栏  ›  技术社区  ›  RobIII Lukas

如何在.NET核心DI中强制创建类的实例?

  •  1
  • RobIII Lukas  · 技术社区  · 6 年前

    我有以下代码:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddOptions();
    
       services.Configure<MyConfig>(Configuration.GetSection("MySection"));
       services.AddSingleton<IMyClass>(sp => new MyClass(sp.GetService<IOptions<MyConfig>>()));
    }
    

    MyClass 现在我可以让我的控制器接受一个 IMyClass . 这是按计划进行的。

    这个 类名 仅当控制器需要 IMY类 . 不过,我想 待实例化

    我可以这样做:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddOptions();
    
       services.Configure<MyConfig>(configuration.GetSection("MySection"));
    
       var myinstance = new MyClass(/*...*/);  // How do I get MyConfig in here?
       services.AddSingleton<IMyClass>(myinstance);
    }
    

    IServiceProvider (The) sp

    2 回复  |  直到 6 年前
        1
  •  3
  •   Nkosi    6 年前

    在这种情况下,真的没有必要 IOptions<T> 因为可以提取配置并将其直接传递给类,但是如果坚持使用选项,则可以使用 OptionsWrapper<TOptions> Class

    IOptions 返回options实例的包装器。

    // How do I get MyConfig in here?
    MyConfig myConfig = configuration.GetSection("MySection").Get<MyConfig>();    
    var wrapper = new OptionsWrapper<MyConfig>(myConfig);
    var myinstance = new MyClass(wrapper);  
    services.AddSingleton<IMyClass>(myinstance);
    

    正在从包装器的配置中提取设置。

    参考 Configuration in ASP.NET Core: Bind to an object graph

        2
  •  1
  •   Eric Damtoft    6 年前

    如果您的主要目标是在任何控制器需要类之前实例化该类,则可以在Startup.cs中的Configure方法中请求它,这样可以保持注册干净,但可以确保它将被初始化。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMyClass myClass)
    {
      myClass.Initialize();
    }
    

    根据需要实例化它的原因,您可能还需要签出 IApplicationLifetime 如果您需要在应用程序启动时连接到推送服务或类似的性质。

    applicationLifetime.ApplicationStarted.Register(() => myConnection.Connect());
    applicationLifetime.ApplicationStopping.Register(() => myConnection.Disconnect());