Castle Windsor注册类与构造函数参数
我有以下课程:
public class DatabaseFactory : Disposable, IDatabaseFactory 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?
如何正确注册它以及如何在运行时传递参数?
您需要注册构造函数参数:
container.Register( Component.For().ImplementedBy() .DependsOn(Dependency.OnValue("connectionString", connectionString)) );
您可以通过添加具有构造函数参数名称的匿名类型来设置Resolve()
方法的依赖项
例:
IDatabaseFactory factory = container.Resolve (new { connectionString = connectionString });