How to constructor-insert a string that is known only at runtime? (Windsor castle)

I have a class that has a string dependency:

public class Person
{
    private readonly string _name;

    public Person(string name)
    {
        if (name == null) throw new ArgumentNullException("name");
        _name = name;
    }
}

This string 'name' is known only at run time, for example. It is defined in the configuration. Therefore, I have this interface that provides this line:

public interface IConfiguration
{
    string Name { get; }
}

Both types, Person and IConfiguration (with its implementation, which is not important here) are registered in the Windsor container.

Question: how can I tell the WindsorCastle container that it should introduce the Name IConfiguration property in the constructor of the Person class?

Caution: I do not want to introduce the IConfiguration class in Person or use typed factories ... the Person class should be simple and take only a string as a parameter.

+4
1

, , , , :

1:

IConfiguration - Name - , :

container.Register(Component.For<IConfiguration>().ImplementedBy<Configuration>());
container.Register(Component
    .For<Person>()
    .DynamicParameters((DynamicParametersDelegate)ResolvePersonName));

// This should be a private method in your bootstrapper 
void ResolvePersonName(IKernel kernel, IDictionary parameters)
{
    parameters["name"] = kernel.Resolve<IConfiguration>().Name;
}

, Person, / Name /. Windsor . , , , :

    .DynamicParameters((k,p) => p["name"] = k.Resolve<IConfiguration>().Name));

2:

Name , Windsor :

container.Register(
    Component.For<Person>()
    .DependsOn(Dependency.OnAppSettingsValue("name", "configSettingKeyName")));

3:

, , , . Person , , Person (?). :

factory:

public interface IPersonFactory
{
    Person Create(string name);
}

, Person, factory :

public class PersonUser
{
    public Personuser(IConfiguration configuration, IPersonFactory personFactory)
    {
        Person person = personFactory.Create(configuration.Name);
    }
}

, :

container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IPersonFactory>().AsFactory());
+4

All Articles