Castle Windsor register class with constructor par

2020-02-24 12:04发布

问题:

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