开发者

How to automaticly register components using a Generic FactoryMethod with Castle Windsor

开发者 https://www.devze.com 2023-03-12 05:21 出处:网络
I´m trying to work out a problem with registering my configuration classes. I have the following in my Installer:

I´m trying to work out a problem with registering my configuration classes. I have the following in my Installer:

First I register my open generic factory

        container.AddFacility<FactorySupportFacility>()
            .Register(Component.For(typeof (IConfigurationProvider<>))
                    .ImplementedBy(typeof (AppSettingsConfigurationProvider<>)));

Then I´m trying to register all concrete impl. of IConfiguration and I need to use my registered impl. IConfigurationProvider to resolve them.

Problem is that my factory looks like this:

public class AppSettingsConfigurationProvider<TConfiguration>
    where TConfiguration : class, IConfiguration, new()
{
    public TConfiguration Build()
    {
        var config = new TConfiguration();

        var properties = typeof(TConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var p in properties)
        {
            if (!p.CanWrite) 
                continue;

            if (p.GetSetMethod(false) == null) 
                continue;

            var settingsKey = string.Format("{0}.{1}", p.ReflectedType.FullName, p.Name);

            p.SetValue(config, Convert.ChangeType(ConfigurationManager.AppSettings[settingsKey], p.PropertyType), null);
        }

        return config;
    }
}

So I need to set the generic type.

Is there a way to get away with this, so that I dont need to register each configuration component one by one like this:

        container
            .Register(
                Component.For<DummyConfiguration>()
                    .ImplementedBy<DummyConfigu开发者_开发技巧ration>()
                        .UsingFactoryMethod(kernel => kernel.Resolve<IConfigurationProvider<DummyConfiguration>>().Build()));

I would prefer a more automatic way to register my configuration componets.


Would something similar to what Ben Hall described, using DictionaryAdapter work for you? Notice that if you're using Windsor 2.5 you already have DictionaryAdapter (it is part of Castle.Core.dll now).

0

精彩评论

暂无评论...
验证码 换一张
取 消