Inject Value from web.config using Castle.Windsor

796 Views Asked by At

I'm migrating some applications to .NET Core and I have to inject a value from web.config.

Using .Net Framework (4.7.2) I did it using Dependency.OnAppSettingsValue. But I cannot find this option any more when I migrate to .NET Core (3.0) or .NET Standard (2.0).

I'm using Castle Windsor (5.0.1) and Castle Core (4.4.0).

container.Register(Component.For<IMigration>()
    .ImplementedBy<SchemaMigration>()
    .LifestyleTransient()
    .DependsOn(Dependency.OnAppSettingsValue("createIndexes", "NHibernate.CreateIndexes")));

How can I do this in .NET Core 3.0?

1

There are 1 best solutions below

0
Martin Cohen On

@Mark Seeman shows how to let windsor provide primitive dependencies from AppSettings in his blogpost.

To resolve from IConfiguration, You can implement a variation like this

public class ConfigurationConvention : ISubDependencyResolver
{
    private readonly Microsoft.Extensions.Configuration.IConfiguration _configuration;

    public ConfigurationConvention(Microsoft.Extensions.Configuration.IConfiguration configuration)
    {
        _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
    }

    public bool CanResolve(
       CreationContext context,
       ISubDependencyResolver contextHandlerResolver,
       ComponentModel model,
       DependencyModel dependency)
    {
        return _configuration[dependency.DependencyKey] != null
            && TypeDescriptor
            .GetConverter(dependency.TargetType)
            .CanConvertFrom(typeof(string));
    }

    public object Resolve(
        CreationContext context,
        ISubDependencyResolver contextHandlerResolver,
        ComponentModel model,
        DependencyModel dependency)
    {
        return TypeDescriptor
            .GetConverter(dependency.TargetType)
            .ConvertFrom(
                _configuration[dependency.DependencyKey]);
    }
}

Add the resolver to windsor by passing the IConfiguration object

container.Kernel.Resolver.AddSubResolver(new ConfigurationConvention(configuration));