Thứ Hai, 24 tháng 11, 2014

Windsor ISubDependencyResolver example

Given the following service:
public class MySuperService
{
  public MySuperService(string connectionString)
  {
    //..
  }
}
I want Windsor automatically to look at the web.config or app.config settings and if there is a configuration with key equals to the parameter name (i.e. “connectionString”) to inject automatically the value when constructing MySuperService instance.
The infrastructure code is this:
public class DependenciesFromAppSettings : AbstractFacility
{
    protected override void Init()
    {
        var dic = ConfigurationManager
            .AppSettings
            .AllKeys
            .ToDictionary(k => k, k => ConfigurationManager.AppSettings[k]);

        Kernel.Resolver.AddSubResolver(new DependenciesFromAppSettingsResolver(dic));
    }
}

public class DependenciesFromAppSettingsResolver : ISubDependencyResolver
{
    private readonly IDictionary webConfig;

    public DependenciesFromAppSettingsResolver(IDictionary webConfig)
    {
        this.webConfig = webConfig;
    }

    public object Resolve(
        CreationContext context, 
        ISubDependencyResolver contextHandlerResolver, 
        ComponentModel model, 
        DependencyModel dependency)
    {
        return webConfig[dependency.DependencyKey];
    }

    public bool CanResolve(
        CreationContext context, 
        ISubDependencyResolver contextHandlerResolver, 
        ComponentModel model, 
        DependencyModel dependency)
    {
        return dependency.DependencyType == DependencyType.Parameter 
            && webConfig.ContainsKey(dependency.DependencyKey);
    }
}
And the usage is very straightforward:
[TestFixture]
public class DependenciesFromAppSettingsTests
{
  [Test]
  public void CanInjectSettingsFromAppConfig()
  {
    var container = new WindsorContainer();

    container.AddFacility<DependenciesFromAppSettings>();
    container.Register(Component.For<MySuperService>());

    var superInstance = container.Resolve<MySuperService>();
    superInstance.ConnectionString
                 .Should().Be.EqualTo("sample conn string");
  } 
}

Không có nhận xét nào: