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

时间:2016-03-27 21:33:39

标签: c# asp.net-mvc autofac n-tier-architecture autofac-module

我通过autofac 模块将图层连接在一起。非常感谢endeffectsHere is the HowTo 现在我正在尝试在DAL层中使连接字符串可用。我试着注册:

Configuration (Microsoft.Extensions.Configuration)

来自 Startup 类但没有任何成功。

非常感谢我们的帮助,谢谢Stefan

2 个答案:

答案 0 :(得分:1)

我在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"]

答案 1 :(得分:0)

我不是我的DAL的粉丝需要知道连接字符串的名称,我不认为这是它的可复制性的一部分。我更喜欢创建自己的界面:

例如,我会创建类似的东西:

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

然后当我使用实体框架与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...
  }
}