Entity framework 实体框架核心DbContext和依赖项注入

Entity framework 实体框架核心DbContext和依赖项注入,entity-framework,dependency-injection,asp.net-web-api2,dbcontext,entity-framework-core,Entity Framework,Dependency Injection,Asp.net Web Api2,Dbcontext,Entity Framework Core,我正在使用Web API、.Net核心和EntityFramework核心构建一个服务应用程序 为了在我的DbContext中配置选项,我在Startup.cs的“ConfigureServices”方法中使用了这些行 var connection = @"Server=ISSQLDEV;Database=EventManagement;Trusted_Connection=True;"; services.AddDbContext<EMContext>(options =>

我正在使用Web API、.Net核心和EntityFramework核心构建一个服务应用程序

为了在我的DbContext中配置选项,我在Startup.cs的“ConfigureServices”方法中使用了这些行

 var connection = @"Server=ISSQLDEV;Database=EventManagement;Trusted_Connection=True;";
 services.AddDbContext<EMContext>(options => options.UseSqlServer(connection));
var connection=@“Server=ISSQLDEV;Database=EventManagement;Trusted_connection=True;”;
services.AddDbContext(options=>options.UseSqlServer(connection));
我知道,如果我将上下文作为构造函数参数添加到控制器中,那么.Net将在构造函数中注入上下文

但这不是我想要的行为。我不想让我的web api知道任何关于dbcontext的信息。我有一个DataAccess项目,它有一个repository类,可以处理所有CRUD操作

这意味着我只想在我的控制器中说Repository.AddEvent(evt),然后Repository知道如何处理它

另一方面,存储库使用一个简单的依赖项解析器来获得正确的“IDataAdapter”实现。其中一个实现是SQLDataAdapter。这是我需要我的背景的一点


我如何将我的上下文一直传递到这一点

您可以通过从数据访问层通过构造函数注入将dbcontext添加到类中来解决这个问题

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(o => o.UseSqlServer(myConnStr));
        services.AddScoped<Repository>(); // 'scoped' in ASP.NET means "per HTTP request"
    }
}

public class MvcController
{
    private Repository repo;
    public MvcController(Repository repo)
    {
        this.repo = repo;
    }

    [HttpPost]
    public void SomeEndpoint()
    {
        this.repo.AddFoo(new Foo());
    }
}

public class Repository
{
    private DbContext db;
    public Repository(ApplicationDbContext db)
    {
        this.db = db;
    }

    public void AddFoo(Foo obj)
    {
        this.db.Set<Foo>().Add(obj);
        this.db.SaveChanges();
    }
}
公共类启动
{
public void配置服务(IServiceCollection服务)
{
services.AddDbContext