Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register string value for concrete name of parameter

I am using Autofac and I have several classes which ask for parameter of type string and name lang. Is there a way to register a string value to all parameters named "lang", so it resolves automatically? I do not want to edit any of the constructors, since it is not my code (I know accepting e.g. CultureInfo would make registration easy..)

Something resulting in short syntax like builder.Register(lang => "en-US").As().Named("lang")

would be ideal.

Thank you.

like image 335
Tomas Grosup Avatar asked Apr 23 '12 10:04

Tomas Grosup


1 Answers

A fairly simple way to solve this is with a custom Autofac module.

First, implement the module and handle the IComponentRegistration.Preparing event. This is also where you'll store the value for your parameter:

using System;
using Autofac;
using Autofac.Core;

public class LangModule : Module:
{
  private string _lang;
  public LangModule(string lang)
  {
    this._lang = lang;
  }

  protected override void AttachToComponentRegistration(
    IComponentRegistry componentRegistry,
    IComponentRegistration registration)
  {
    // Any time a component is resolved, it goes through Preparing
    registration.Preparing += InjectLangParameter;
  }

  protected void InjectLangParameter(object sender, PreparingEventArgs e)
  {
    // Add your named parameter to the list of available parameters.
    e.Parameters = e.Parameters.Union(
      new[] { new NamedParameter("lang", this._lang) });
  }
}

Now that you have your custom module, you can register it along with your other dependencies and provide the value you want injected.

var builder = new ContainerBuilder();
builder.RegisterModule(new LangModule("my-language"));
builder.RegisterType<LangConsumer>();
...
var container = builder.Build();

Now when you resolve any type that has a string parameter "lang" your module will insert the value you provided.

If you need to be more specific, you can use the PreparingEventArgs in the event handler to determine things like which type is being resolved (e.Component.Activator.LimitType), etc. Then you can decide on the fly whether to include your parameter.

like image 100
Travis Illig Avatar answered Nov 20 '22 02:11

Travis Illig