stevo
stevo

Reputation: 2284

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

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.

Upvotes: 3

Views: 921

Answers (2)

Erik Philips
Erik Philips

Reputation: 54618

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...
  }
}

Upvotes: 0

Jeremy Armstrong
Jeremy Armstrong

Reputation: 945

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

Upvotes: 1

Related Questions