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.
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"]
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...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.