问题
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.
回答1:
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.
回答2:
Have a look at this example:
builder.Register<ClassName>((c, p) =>
{
var p2 = p.Named<string>("lang");
return new ClassName(p2);
});
var container = builder.Build();
var m = container.Resolve<ClassName>(new NamedParameter("lang", "en-US"));
var m2 = container.Resolve<ClassName>(new NamedParameter("lang", "fr-FR"));
you can resolve your class and pass parameters in constructor.
来源:https://stackoverflow.com/questions/10279088/register-string-value-for-concrete-name-of-parameter