在ASP.NET Core中,可以通过使用AddDbContext
方法将IdentityContext
注册到依赖注入容器中,而无需在构造函数中指定参数。以下是一个示例解决方案:
Startup.cs
文件中的ConfigureServices
方法中添加以下代码:services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
这将注册IdentityContext
并使用SQL Server作为数据库提供程序。
IdentityContext.cs
文件中,确保构造函数带有DbContextOptions
参数,如下所示:public class IdentityContext : DbContext
{
public IdentityContext(DbContextOptions options) : base(options)
{
}
// 其他代码
}
通过这样做,IdentityContext
将能够通过依赖注入获得所需的DbContextOptions
参数。
请注意,确保在appsettings.json
文件中配置了名为DefaultConnection
的数据库连接字符串。可以使用以下示例配置:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
},
// 其他配置
}
这是一个示例解决方案,您可以根据自己的需求进行调整。