Castle Windsor注册类与构造函数参数

时间:2013-11-27 13:15:14

标签: c# castle-windsor

我有以下课程:

public class DatabaseFactory<C> : Disposable, IDatabaseFactory<C> where C : DbContext, BaseContext, new()
{
    private C dataContext;
    private string connectionString;

    public DatabaseFactory(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public C Get()
    {
        return dataContext ?? (dataContext = Activator.CreateInstance(typeof(C), new object[] {connectionString}) as C);
    }

    protected override void DisposeCore()
    {
        if (dataContext != null)
            dataContext.Dispose();
    }
}

当我尝试启动web api时,出现以下错误:

Can't create component 'MyApp.DAL.Implementations.DatabaseFactory'1' as it has dependencies to be satisfied. 'MyApp.DAL.Implementations.DatabaseFactory'1' is waiting for the following dependencies: - Parameter 'connectionString' which was not provided. Did you forget to set the dependency?

如何正确注册,如何在运行时传递参数?

2 个答案:

答案 0 :(得分:38)

您需要注册构造函数参数:

container.Register(
    Component.For<IDatabaseFactory>().ImplementedBy<DatabaseFactory>()
             .DependsOn(Dependency.OnValue("connectionString", connectionString))
    );

答案 1 :(得分:10)

您可以通过添加带有构造函数参数名称

的匿名类型来设置Resolve()方法的依赖项

示例:

IDatabaseFactory factory = container.Resolve<IDatabaseFactory>
                           (new { connectionString = connectionString });