如何使用 Autofac 使连接字符串在 N 层 ASP.NET MVC Core 1.0 应用程序中可用

How to make the connection string available in a N-Tier ASP.NET MVC Core 1.0 App with Autofac

我通过 autofac modules 将层连接在一起。非常感谢 endeffects. 。现在我正在尝试使连接字符串在 DAL 层中可用。我尝试注册:

Configuration (Microsoft.Extensions.Configuration)

启动 class但没有任何成功。

我在 startup.cs 的 ConfigureServices 方法中有以下行:

services.AddSingleton(serviceType => Configuration);
services.AddInstance<Microsoft.Extensions.Configuration.IConfiguration>(Configuration);

builder.Populate(services);
var container = builder.Build();
var serviceProvider = container.Resolve<IServiceProvider>();
return serviceProvider;

然后在我的 DAL 中,我通过构造函数注入访问它,例如:

public MyDataContext(IConfiguration configurations)

然后我可以访问该项目并提取我的连接信息,例如:

configurations["Data:MyConnection:ConnectionString"]

我不喜欢我的 DAL 需要知道关于连接字符串名称的任何信息,我不认为这是它的责任的一部分。我更喜欢创建自己的界面:

例如,我会创建如下内容:

public interface IConnectionSettings
{
  public ConnectionStringSettings DataWarehouse { get; }
  public ConnectionStringSettings Audit { get; }
  public ConnectionStringSettings Logging { get; }
  public ConnectionStringSettings Security { get; }
}

然后当我使用 Entity Framework 和 DI

public class SecurityContext : DbContext
{
  public SecurityContext(IConnectionSettings settings)
    : base (settings.Name)
  {
  }
}

或 ADO.Net 出于某种奇怪的原因:

public class LoggingDataAccess
{
  private readonly string _connectionString;

  public LoggingDataAccess(IConnectionSettings settings)
  {
    _connectionString = settings.Logging.ConnectionString;
  }

  public void SomeRawAdo()
  {
    using (var con = new Connection(_connnectionstring))
    {
    }
  }
}

在我的 DI 中:

public static class IocCOnfig
{
  public static void Start()
  {
    var builder = new ContainerBuilder();

    builder.Register(r => new ConnectionSettings
    {
      DataWarehouse = ConfigurationManager.ConnectionStrings["DataWarehouse"],
      // etc
    });
  }

  private class ConnectionSettings : IConnectionSettings
  {
    // implement interface...
  }
}