简体   繁体   中英

How to pass parameter to an Autofac Module from a resolve dependency

Currently I have a autofac module which receives a string as parameter, and that string is coming from another dependency.

Im trying to pass it using below code, my question is: Is this the right approach or there is a better/improved way to do it?

builder.RegisterBuildCallback(c =>
{
    var configService = c.Resolve<IConfigurationService>();
    var module = new LoggingModule(configService.GetConfigurationValue("LoggerName"));
    module.Configure(c.ComponentRegistry);
});

Generally try to avoid build callbacks and trying to configure the container based on configuring the container. To be honest, I'm surprised this even works since the container and registry are effectively immutable .

It would be better to use a lambda registration to resolve things. Since we don't know what your logging module is doing, let's say right now it's this:

public class LoggingModule
{
  private readonly string _name;
  public LoggingModule(string name)
  {
    this._name = name;
  }
  protected override void Load(ContainerBuilder builder)
  {
    builder.RegisterInstance(new MyLogger(this._name));
  }
}

Even if it's not exactly this, it's pretty easy to adapt something similar - the parameter is coming into the module and being used by a registration.

You could move that into the registration itself and remove the module entirely.

builder.Register(ctx =>
{
  var configService = ctx.Resolve<IConfigurationService>();
  var name = configService.GetConfigurationValue("LoggerName");
  return new MyLogger(name);
}).SingleInstance();

This avoids having to "know the parameter up front" and also avoids trying to reconfigure the container. You still get to register the config in DI and resolve it like you want.

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