【发布时间】:2020-01-22 14:05:51
【问题描述】:
这里有很多关于如何做到这一点的帖子,但无论我尝试什么配置,我似乎都无法获得我的数据库连接字符串。 startup.cs 是从 Microsoft 项目模板为 Core 2.2 自动配置的,据我所知,它没有任何问题。我没有使用 EF,也不想加载一些第 3 方黑匣子来让它工作。
这是 Startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TestWebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
这是 appsettings.json 文件:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=mydbserver;Initial Catalog=mydatabase;Integrated Security=True;Persist Security Info=False;"
}
}
在另一篇文章中,以下内容应该有效,但无效:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestAppWithService
{
public class TestDB
{
string conString = Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(this.Configuration, "DefaultConnection");
}
}
名为 TestDB.cs 的文件被设置为编译,并且,我把它放在根文件夹中(不管我把类放在哪里:模型、控制器等) 我得到关键字“this”在当前上下文中不可用。 (下面有一条波浪线)。 我不知道如何继续或寻找什么,这里的答案很多,有各种各样的调整,但根据 MS,这应该可以正常工作。 我是 dotnetcore 的新手,并认为我已经弄清楚了这种依赖注入的东西,但仍然卡住了。
【问题讨论】:
-
与你当前的错误有关,见stackoverflow.com/a/1920814/5394220
-
我不确定如何初始化在 Startup.cs 中创建的配置。
-
@MC9000 你不知道。在这种情况下,它被注入到启动中。
标签: c# asp.net-core dependency-injection .net-core configuration