Autofac在运行时解析参数

时间:2014-09-01 09:15:37

标签: c#-4.0 connection-string autofac

让我们直截了当。 我有这样的接口和类:

public interface IDataBase
{
    DataTable GetSomeTableData();
}

我的课程:

public class DataBase : IDataBase    
{
    private readonly string _connectionString;

    public DataBase(string connectionString)
    {
        this._connectionString = connectionString;
    }

    public DataTable GetSomeTableData()
    {
        using (SqlConnection cn = new SqlConnection(_connectionString))
        {
             cn.Open();
             // some select
        }
    }
}

我使用Autofac注入该类:

var builder = new ContainerBuilder();
builder.RegisterType<DataBase>().As<IDataBase>).WithParameter("connectionString", "my connection string");
var container = builder.Build();
var database = container.Resolve<IDataBase>();
var tableData1 = database.GetSomeTableData();
// change connection string ?????????????????
var tableData2 = database.GetSomeTableData();

我需要从一个DB和另一个DB获取表数据。如何在注册课程后更改连接字符串?你可以提出另一个例子..

1 个答案:

答案 0 :(得分:7)

许多方法可以做到这一点。一种是创建和注入服务,而不仅仅是普通的连接字符串。

public interface IConnectionStringProvider
{
    public string ConnectionString { get; set }
}

public class ConnectionStringProvider
{
    public string ConnectionString { get; set }
}


var builder = new ContainerBuilder();
builder.RegisterType<DataBase>()
    .As<IDataBase>);
builder.RegisterType<ConnectionStringProvider>)
    .As<IConnectionStringProvider>
    .SingleInstance();

var container = builder.Build();
var database = container.Resolve<IDataBase>();
var connStringProvider = container.Resolve<IConnectionStringProvider>();
var tableData1 = database.GetSomeTableData();
connStringProvider.ConnectionString = "...";
var tableData2 = database.GetSomeTableData();

然后DataBase将使用该服务:

public class DataBase : IDataBase    
{
    private readonly IConnectionStringProvider _connectionStringProvider;

    public DataBase(IConnectionStringProvider connectionStringProvider)
    {
        this._connectionStringProvider = connectionStringProvider;
    }

    public DataTable GetSomeTableData()
    {
        using (SqlConnection cn = new SqlConnection(_connectionStringProvider.ConnectionString))
        {
             cn.Open();
             // some select
        }
    }
}