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.
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:
Now that you have your custom module, you can register it along with your other dependencies and provide the value you want injected.
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.