Windsor城堡在嵌套类中注入依赖关系,并在运行时解析根接口

时间:2017-07-20 20:40:31

标签: c# dependency-injection castle-windsor

我有一系列类和接口,我使用依赖注入。问题是“root”接口在运行时被解析。因此,我不知道如何使用Windsor Castle为层次结构中的“更高”接口注入依赖项。

以下是一个例子:

public interface IConnectionSettings
{
    string ConnectionString { get; }
}

public class TestEnvironmentConnectionSettings
{
    string ConnectionString { get; }

    public TestEnvironmentConnectionSettings(EEnvironment environment)
    {
        ConnectionString = "ConnectionStringTo" + environment;
    }
}

public interface IDatabaseConnection
{
    IEnumerable<T> RunQuery<T>(string query);
}

public class DatabaseConnection : IDatabaseConnection
{
    private readonly IConnectionSettings _connectionSettings;

    public DatabaseConnection(IConnectionSettings connectionSettings)
    {
        _connectionSettings = connectionSettings;
    }

    public IEnumerable<T> RunQuery<T>(string query)
    {
        // do something and return results
    }
}

public interface IPersonConnection
{
    Person GetPerson(int id);
}

public class PersonConnection : IPersonConnection
{
    private readonly IDatabaseConnection _databaseConnection;

    public PersonConnection(IDatabaseConnection databaseConnection)
    {
        _databaseConnection = databaseConnection;
    }

    public GetPerson(int id)
    {
        // prepare query and return results
    }
}

问题是,一旦我知道将使用哪个EEnvironment,我想获得PersonConnection的实例。但现在我必须构建TestEnvironmentConnectionSettings以获取DatabaseConnection并获取PersonConnection等.Canor Castle可以帮助我这样做,所以我不必创建工厂吗?或者我的代码设计错误了吗?

1 个答案:

答案 0 :(得分:1)

如果您没有直接向构造函数提供EEnvironment,而是提供一个接口,而不是提供EEnvironment(来自配置,数据库,等等),并使用以下命令注册所有组件适当的非单一生活方式(瞬态,范围等)然后当您从Castle Windsor容器中解析PersonConnection时,依赖关系也将被解析并建立适当的数据库连接。