依赖注入 - AddDbContext

时间:2017-02-14 21:26:17

标签: c# dependency-injection asp.net-core entity-framework-core

我是DI的新手,正在努力学习我的绳索。

我正在尝试在aspnet核心上创建一个webapi,我使用依赖注入创建一个存储库来利用数据实体框架核心。我的目标是首先尝试将它与Sql服务器一起使用,看看它是如何运行的,这样我以后可以将其扩展为与Oracle一起使用。

这是我测试的结构:

enter image description here

我的目的是创建一个名为ReceiptRepository的Repository,它实现了IReceiptRepository,并且只依赖于ReceiptDbContext,它保存了我想要访问的数据库的上下文。

在StartUp.cs上,我将DI注入服务

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
(optionBuilder.Options);
            //services.AddDbContext<dbContext>();
            services.AddDbContext<ReceiptDbContext>(Options => Options.UseSqlServer(connection));
            services.AddScoped<IReceiptRepository, ReceiptRepository>();
            services.AddMvc();
            services.AddMemoryCache();
        }

项目编译没有错误,但是当我用邮递员检查时,没有返回任何数据,尽管我的数据库有数据。

enter image description here

进一步检查会在receiptController

中的GetAll()函数中显示异常
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using TestReceipt.Core.Intefaces;
using TestReceipt2.Models;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace TestReceipt2.Controllers
{
    [Route("api/[controller]")]
    public class ReceiptController : Controller
    {
        private readonly IReceiptRepository _receiptRepository;

        public ReceiptController(IReceiptRepository receiptRepository)
        {
            _receiptRepository = receiptRepository;
        }

        public IActionResult Index()
        {
            return View(_receiptRepository.GetAll());
        }
        // GET: api/values
        [HttpGet]
        [ResponseCache(Duration =60, Location =ResponseCacheLocation.Client)]
        public IEnumerable<Receipt> GetAll()
        {
            return _receiptRepository.GetAll();
        }

        // GET api/values/5
        [HttpGet("{id}",Name ="GetReceipt")]
        public IActionResult Get(string id)
        {
            var Item = _receiptRepository.Find(id);
            if (Item==null)
            {
                return NotFound();
            }
            return new ObjectResult(Item);
        }

        // POST api/values
        [HttpPost]
        public IActionResult Post([FromBody]Receipt value)
        {
            if (value==null)
            {
                return BadRequest();
            }
            TryValidateModel(value);
            if (this.ModelState.IsValid)
            {
                _receiptRepository.Add(value);
            }
            else
            {
                return BadRequest();
            }
            return CreatedAtRoute("GetCustomer", new { controller = "Receipt", id = value.ID });
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public IActionResult Put(string id, [FromBody]Receipt value)
        {
            var receipt = _receiptRepository.Find(id);
            _receiptRepository.Update(value);
            return new NoContentResult();
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(string id)
        {
            _receiptRepository.Remove(id);
        }
    }
}

例外:

enter image description here

我想我可能知道错误的原因。 ReceiptDBContext可能未在Startup.cs中正确注入,因此无法使用。但是,我不知道如何纠正我的错误。

我试过了:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    var optionBuilder = new DbContextOptionsBuilder();
        optionBuilder.UseSqlServer(connection);
    var dbContext = new ReceiptDbContext(optionBuilder.Options);

    services.AddDbContext<dbContext>(); // Compiler error...


    Services.AddScoped<IReceiptRepository, ReceiptRepository>();
    services.AddMvc();
    services.AddMemoryCache();
}

但编译器对“我的修复”不满意。请帮忙!

我的project.json

{
    "dependencies": {
        "Microsoft.AspNetCore.Mvc": "1.0.1",
        "Microsoft.AspNetCore.Routing": "1.0.1",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
        "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
        "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",
        "Microsoft.Extensions.Caching.Abstractions": "1.1.0",
        "Microsoft.Extensions.Caching.Memory": "1.1.0",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
        "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
        "Microsoft.Extensions.Configuration.Json": "1.0.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.0.0",
        "Microsoft.Extensions.Logging.Debug": "1.0.0",
        "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
        "Microsoft.NETCore.App": {
            "version": "1.0.1",
            "type": "platform"
        }
    },

  "tools": {
            "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
            "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

0 个答案:

没有答案