加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 如何从控制器中解析ASP NET 5中的EF7当前数据库

发布时间:2020-12-16 07:06:39 所属栏目:asp.Net 来源:网络整理
导读:我想在ASP NET 5 / EF 7应用程序中为每个请求获取一个上下文,以便在某些方法中使用它(不在控制器中). 不幸的是我没有在文档中找到答案 ASP.NET vNext template和例子aspnet/MusicStore 解决方法 您可以使用某些方法来实现此目的. 使用.AddDbContext Applicat
我想在ASP NET 5 / EF 7应用程序中为每个请求获取一个上下文,以便在某些方法中使用它(不在控制器中).

不幸的是我没有在文档中找到答案
ASP.NET vNext template和例子aspnet/MusicStore

解决方法

您可以使用某些方法来实现此目的.

使用.AddDbContext< ApplicationDbContext>();在依赖注入系统中注册ApplicationDbContext的方法(在ConfigureServices()方法中)导致它注册为Scoped依赖(或者换言之“每个请求”).因此,您只需要从依赖注入系统获取它.

>将dbContext作为构造函数方法的参数添加到您的类中(您将使用dbContext).然后你必须使用依赖注入系统来获得这个类,例如将它添加为控制器构造函数的参数.

public class HabitsController : Controller
{
    public HabitsController(HabitService habitService)
    {

    }
}

public class HabitService
{
    private GetHabitsContext _dbContext;

    public HabitService(GetHabitsContext dbContext)
    {
        _dbContext = dbContext;
    }
}

>但是如果你不想使用构造函数注入来获取上下文,你可以使用GetService()方法得到必要的依赖项(但是你需要在ServiceProvider实例中,在下面的示例中,我也可以通过构造函数注入) .

using Microsoft.Framework.DependencyInjection; // for beta 6 and below
using Microsoft.Extensions.DependencyInjection; // for beta 7 and above
public class HabitService
{
    private IServiceProvider _serviceProvider;

    public HabitService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public GetHabit()
    {
         var dbcontext = _serviceProvider.GetService<ApplicationDbContext>();
    }
}

>在第一种方法中,我们也可以通过GetService()方法获取HabitService(而不是通过构造函数注入).

using Microsoft.Framework.DependencyInjection; // for beta 6 and below
using Microsoft.Extensions.DependencyInjection; // for beta 7 and above

public class HabitsController : Controller
{
    public HabitsController(IServiceProvider serviceProvider)
    {
       var habitService= serviceProvider.GetService<HabitService>();
    }
}

public class HabitService
{
    private GetHabitsContext _dbContext;

    public HabitService(GetHabitsContext dbContext)
    {
        _dbContext = dbContext;
    }
}

谢谢Tseng的评论:

I should be noted,that it’s a pretty bad practice to inject the container into your objects. The container should only be referenced from the composition root and certain type of factories (which are implemented on application level,and not in the domain/business layer)

dbContext in HabitsController and _dbContext in HabitService are different contexts!

我检查过,这是相同的背景.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读