Castle Windsor register class with constructor parameters

Ivan-Mark Debono picture Ivan-Mark Debono · Nov 27, 2013 · Viewed 21.5k times · Source

I have the following class:

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();
    }
}

When I try to start the web api, I get the following error:

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?

How do I register it correctly and how do I pass the parameter at runtime?

Answer

Ufuk Hacıoğulları picture Ufuk Hacıoğulları · Nov 27, 2013

You need to register the constructor parameter:

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