Castle Windsor register class with constructor parameters
22,964
Solution 1
You need to register the constructor parameter:
container.Register(
Component.For<IDatabaseFactory>().ImplementedBy<DatabaseFactory>()
.DependsOn(Dependency.OnValue("connectionString", connectionString))
);
Solution 2
You can set dependencies on Resolve()
method by adding an anonymous type with constructor parameter's name
Example:
IDatabaseFactory factory = container.Resolve<IDatabaseFactory>
(new { connectionString = connectionString });
Author by
Ivan-Mark Debono
Updated on April 26, 2020Comments
-
Ivan-Mark Debono about 4 years
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?