3

I wired the layer together via autofac modules. Big thanks to endeffects. Here is the HowTo. Now I'm trying to make the connection string available in the DAL layer. I tried to register the:

Configuration (Microsoft.Extensions.Configuration)

From the Startup class but without any success.

halfer
  • 19,824
  • 17
  • 99
  • 186
stevo
  • 2,164
  • 4
  • 23
  • 33

2 Answers2

1

I have the following line in my ConfigureServices method in startup.cs:

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;

Then in my DAL, I access that via constructor injections like:

public MyDataContext(IConfiguration configurations)

I can then access that item and pull my connection info like:

configurations["Data:MyConnection:ConnectionString"]
Jeremy Armstrong
  • 885
  • 9
  • 22
  • Thanks @Jeremy Armstrong but I'm using autofac and not the DI from ASP.NET Core. But I'm trying basically the same with autoface... – stevo Mar 27 '16 at 22:12
  • Edited my answer with the remaining code to populate your services into your autofac builder, and then return the appropriate service provider. – Jeremy Armstrong Mar 27 '16 at 22:17
  • 1
    `AddInstance` has been renamed to `AddSingleton` https://github.com/aspnet/Announcements/issues/119 – Eonasdan Mar 27 '17 at 19:35
0

I'm not a fan of my DAL needing to know anything about the name of the connection string, I don't think that is part of it's repsonsibility. I prefer creating my own interface:

So for instance I would create something like:

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

Then when I'm using Entity Framework with DI

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

Or ADO.Net for some weird reason:

public class LoggingDataAccess
{
  private readonly string _connectionString;

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

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

In my 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...
  }
}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150