刚开始使用.Net Core并将连接字符串信息传递给Context控制台项目.
我有4个项目,使用.Net Core创建.
在MVC项目中,我有Startup.cs文件,我正在阅读appsettings.json文件
    public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc();
            // Add appsettings
            services.Configure<AppSettingsConfig>(Configuration.GetSection("AppSettings")); 
}
public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        if (env.IsDevelopment())
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }
在我的第4个项目(Data Layer)中,有哪个Console Project并且有以下DBContext类.这个项目没有像我MVC项目那样的Startup.cs.不是由VS 2015默认创建的.
public class MyDWContext : DbContext
{
    public MyDWContext() : base ()
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {            
        optionsBuilder.UseSqlServer(@"Data Source=localhost;Initial Catalog=MyDW; Persist Security Info = False; User ID = TempUser; Password = Temp123");
    }
    public DbSet<User> Users { get; set; }
    public DbSet<Class> Classs { get; set; }
}
我也去过其他帖子,但我相信它是使用旧版本或RC版本创建的.所以有一段时间我找不到正确的对象或.Net类.
因为我有连接字符串是在MVC项目中,我如何在我的MVC调用数据层期间使用连接字符串.
我也有Web.API(Core)项目,并且拥有自己的连接字符串(连接字符串中只有读访问权限的不同用户配置).当我从Web2.API项目调用时,如何使用Web2.API连接字符串.
相反,通过连接字符串的DbContext,配置DbContext的Startup.cs(如果可能)是更好的办法.请参阅官方文档以了解如何DbContext通过依赖注入配置和使用它.
编辑:下面的代码不是很好的方法
但是,如果要将连接字符串传递给DbContext您,可以使用选项模式.
以下是如何使用选项模式传递连接字符串的示例:
首先,您需要一个可从Data Layer和MVC层访问的选项类
public class ConnectionStringOption
{
     public string ConStr { get ; set; }
}
然后设置选项值
public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<ConnectionStringOption>(options=>
     {
         // set connection string from configuration  
         options.ConStr = Configuration.GetConnectionString("Default");
     });      
}
appsetting.json
{
  "ConnectionStrings": {
    "Default": "<your connection string>"
  }
}
最后 DbContext
    private readonly IOptions<ConnectionStringOption> _conStrOptions;
    protected YourDbContext()
    {
    }
    public YourDbContext(IOptions<ConnectionStringOption> conStrOptions, DbContextOptions options) 
        : base(options)
    {
        _conStrOptions= conStrOptions;
    }
编辑另一种方式
使用静态服务定位器可能是一个解决方案:
DependencyResolver在数据层中创建
public static class DependencyResolver
{
    private static IServiceProvider _provider;
    public static IServiceProvider ServiceProvider
    {
        get
        {
            return _provider;
        }
        set
        {
            if(_provider == null)
            {
                _provider = value;
            }
        }
    }
}
在ConfigureServices方法中
    public void ConfigureServices(IServiceCollection services)
    {
        // other stuff
        services.AddOptions();
        services.Configure<ConnectionStringOption>(options=>
        {
            // set connection string from configuration  
            options.ConStr = Configuration.GetConnectionString("Default");
        }); 
        DependencyResolver.ServiceProvider = services.BuildServiceProvider();
    }
最后得到选项:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{            
    var conStr = DependencyResolver.ServiceLocator.GetService<IOptions<ConnectionStringOption>>().Value.ConStr;
    optionsBuilder.UseSqlServer();
}
最后编辑以前的愚蠢方式
public static class ConnectionStringGetter
{
    public static string ConStr{get;set;}
}
public Startup(IHostingEnvironment env)
{
    //...
    Configuration = builder.Build();
    ConnectionStringGetter.ConStr =  Configuration.GetConnectionString("Default");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{            
    optionsBuilder.UseSqlServer(ConnectionStringGetter.ConStr);
}
| 归档时间: | 
 | 
| 查看次数: | 5064 次 | 
| 最近记录: |