Castle Windsor register class with constructor parameters

守給你的承諾、 提交于 2019-11-29 05:11:48

问题


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?


回答1:


You need to register the constructor parameter:

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



回答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 });


来源:https://stackoverflow.com/questions/20243543/castle-windsor-register-class-with-constructor-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!