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

974 views Asked by At

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);
});
1

There are 1 answers

0
Travis Illig On BEST ANSWER

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.