在我的MVC 6项目中,我上了ApplicationDBContext
课
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
}
}
这已添加到我在Startup.cs中的服务中
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
//Other configurations removed for brevity
}
现在,当我创建一个新的Controller时,它会问我是否要使用Entity Framework,并且可以选择我的数据上下文。当创建该控制器时,使用我假设的依赖项注入在构造函数中传递上下文。
public class CompanyController : Controller
{
private ApplicationDbContext _context;
public CompanyController(ApplicationDbContext context)
{
_context = context;
}
}
现在,我不想在控制器中进行所有数据库交互,而是在其他类中进行。我不知道的是如何从其他类中获取ApplicationDbContext。从控制器传递它显然是行不通的,因为可以从控制器以外的其他地方调用类。
如果我只是尝试new ApplicationDbContext();
,则会出现以下错误:
No database providers are configured. Configure a database provider by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
我觉得这应该很简单,但是我在这里完全迷失了。
ASP.NET Core基于依赖项注入,因为您的上下文已添加到依赖容器中,所以在实例化控制器时,框架会自动注入它。
您可以设置类以支持DI,假设您有两个类。一个取决于您的上下文,其次取决于您的上下文和您的第一堂课:
public class MyClass
{
private ApplicationDbContext _context;
public MyClass(ApplicationDbContext context)
{
_context = context;
}
}
public class AnotherClass
{
private ApplicationDbContext _context;
private MyClass _myClass;
public AnotherClass(ApplicationDbContext context, MyClass myClass)
{
_context = context;
_myClass = myClass;
}
}
在启动时,将您的类作为临时依赖项添加到服务集合中,并让服务提供商为您解决它们的依赖项:
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddTransient<MyClass>();
services.AddTransient<AnotherClass>();
//Other configurations removed for brevity
}
更改您的控制器以接受MyClass作为注入依赖项:
public class CompanyController : Controller
{
private ApplicationDbContext _context;
private MyClass _myClass;
public CompanyController(ApplicationDbContext context, MyClass myClass)
{
_context = context;
_myClass = myClass;
}
}
您还可以拥有另一个将AnotherClass作为注入依赖的控制器:
public class AnotherController : Controller
{
private AnotherClass _anotherClass;
public AnotherController(AnotherClass anotherClass)
{
_anotherClass = anotherClass;
// _anotherClass will have both ApplicationDbContext and MyClass injected by the service provider
}
}
您应该阅读ASP.NET Core依赖项注入的文档,它可以帮助您了解DI的基础。K. Scott Allen的另一篇文章解释了在处理DI时的一些不良做法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句