简体   繁体   中英

Autofac - resolve by argument name

I'm migrating an application from Ninject to Autofac.

We used a special naming convention for injecting app settings into constructors:

public class Example{
    public Example(AppSetting settingName){
        ...
    }
}

AppSetting parameter was injected automatically using ConfigurationManager.AppSettings["settingName"].

In Ninject this was accomplished by using a custom provider:

public class AppSettingProvider : Ninject.Activation.IProvider
{

    public object Create(IContext context)
    {
        var varName = ((Context)context).Request.Target.Name;
        var value = new AppSetting(ConfigurationManager.AppSettings[varName]);

        if (value.Value == null)
        {
            ... log ...
        }
        return value;
    }

    public Type Type
    {
        get { return typeof(AppSetting); }
    }

}

I was not able to find an alternative for this feature in Autofac. If this is not possible in an automated way I'm ok with looping over all app settings during the initial configuration step.

Any idea what to do?

Thanks, Vilem

I have created a solution using this SO question: Register string value for concrete name of parameter

and subsequently improved it using Travis Illig's suggestion.

Currently this seems to work exactly the same as the Ninject equivalent.

Here's the result:

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

    private void InjectAppSettingParameters(object sender, PreparingEventArgs e)
    {
        // check if parameter is of type AppSetting and if it is return AppSetting using the parameter name
        var appSettingParameter = new ResolvedParameter((par, ctx) => par.ParameterType == typeof(AppSetting), (par, ctx) => new AppSetting(ConfigurationManager.AppSettings[par.Name]));
        e.Parameters = e.Parameters.Union(new List<Parameter>{ appSettingParameter});
    }
}

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