简体   繁体   中英

Autofac - upgrading from .net core 2.2 to 3.1

i'm following Autofac guide to migrate to .net 3.1

According to their guide, I need to add (among other things) this function:

public void ConfigureContainer(ContainerBuilder builder)

And this will be called automatically

The problem is that the code inside it that is registering the services is conditional for our app so I need to pass a boolean to the function

for example:

public void ConfigureContainer(ContainerBuilder builder)
{
 if (enableTokenAutoRefresh)
 {
   builder.RegisterType<AuthenticationWrapper>()
    .As<IApiProxy>()
 }
 else
 {
   builder.RegisterType<ApiProxy>()
    .As<IApiProxy>()
 }
}

Can I just add a boolean to the ConfigureContainer method? seems this will break the calling for it? and if not - how to pass data to it ?

please help

ConfigureContainer , provided by the ASP.NET Core framework, only takes the container builder type of your DI framework (in this case, an Autofac ContainerBuilder ). To get additional data in there, you'd need to set a variable on the Startup class somewhere earlier in the startup pipeline and use it.

// NOT a complete Startup, but gives you the idea.
public class Startup
{
  public Startup(IConfiguration config)
  {
    // appSettings.json has the value you want
    this.EnableTokenAutoRefresh = config.GetValue<bool>("path:to:key");
  }

  public bool EnableTokenAutoRefresh { get; set; }

  public void ConfigureContainer(ContainerBuilder builder)
  {
    if(this.EnableTokenAutoRefresh)
    {
      // Do what you need to based on config
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM