【发布时间】:2020-04-16 07:31:06
【问题描述】:
这个问题有很多答案,如果您使用的是 MVC,但如果您不使用 MVC 怎么办?我有一堂Student,里面有所有的Crud。由于对类的调用,我无法使用任何示例。我是 Core 新手,但使用 Web 表单和 MVC 已有一段时间了。
当我拨打电话时,例如:
Student s = new Student();
s.FullName = "Sam";
s.Update;
我收到需要 IConfiguration 或 IOptions 的错误,这取决于我尝试调用 AppSettings 的方式。
Startup.cs
IConfigurationSection appSetting = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSetting);
学生班
public class Student
{
private readonly IOptions<AppSettings> _appSetting;
public Student(IOptions<AppSettings> appSettings)
{
_appSetting = appSettings;
}
它在 Student 类中的调用位置
public Student GetStudent(Guid StudentGUid)
{
var Conn = _appSetting.Value.ApplicationConn;
using (IDbConnection con = new SqlConnection(Conn))
{
我在页面 .cs 上调用类的地方
Student sa = new Student();
sa.GetStudent(new Guid("2b583b82-0337-425b-ac73-3830bc20253f"));
var s = sa.LastName;
错误:
*没有给出与所需形参'appSetting ....相对应的参数,这是有道理的。但这是我出轨的地方,因为我不能只输入 IOption 值,因为它总是为空。
AppSettings 类
public class AppSettings
{
public string ApplicationID { get; set; }
public string ApplicationUrl { get; set; }
public string ApplicationConn { get; set; }
}
JSON 文件
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AppSettings": {
"ApplicationID": "Some Guid",
"ApplicationUrl": "xxxxxx",
"ApplicationConn": "Connection String"
},
"AllowedHosts": "*"
【问题讨论】:
-
为什么
Student需要了解应用程序设置?看来您的设计是这里的问题。 -
这是我拉连接字符串的地方。
-
同样,
Student对象永远不需要知道连接字符串——这不是它的责任。相反,您应该拥有某种存储库来检索和持久化Student对象。 -
我明白了,但是我们的对象类是自包含的,其中包含 CRUD 操作。因此需要一个连接字符串,app Id ... ectra
标签: c# asp.net asp.net-core .net-core