带构造函数参数的Castle

带构造函数参数的Castle

本文介绍了带构造函数参数的Castle Windsor注册类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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

当我尝试启动网络api时,以下错误:

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

无法创建组件'MyApp.DAL.Implementations.DatabaseFactory'1',因为它具有要满足的依赖关系。 MyApp.DAL.Implementations.DatabaseFactory 1正在等待以下依赖项:
-未提供参数 connectionString。您忘记设置依赖项了吗?

如何正确注册它以及如何在运行时传递参数?

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

推荐答案

您需要注册构造函数参数:

You need to register the constructor parameter:

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

这篇关于带构造函数参数的Castle Windsor注册类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:37