【问题标题】:ASP.NET Core database configuration with dependency injection issue具有依赖注入问题的 ASP.NET Core 数据库配置
【发布时间】:2017-02-12 12:14:34
【问题描述】:

我在 6 天前遇到了一个问题,但我仍然无法解决。

我正在使用 DI 设置 DBContext:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

数据库文件路径在appsettings.json中配置

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=xxxx.db"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

我正在创建这样的 DBContext (https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext)

public class ApplicationContext : DbContext
{
        public DbSet<Network> xxxx { get; set; }
        public DbSet<NetworkEntry> xxxx { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
        { }
}

我的控制器代码:

public JsonResult Index(ApplicationContext db)
{
    return Json(db.Networks);
}

它编译并运行。如果我使用其他配置数据库的方式,它可以 100% 无问题地工作:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlite("Filename=./blog.db");
}

我遇到的问题:

System.InvalidOperationException: Could not create a model binder for model object of type 'xxx.Data.ApplicationContext'.
   at Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderFactory.CreateBinder(ModelBinderFactoryContext context)
   at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerArgumentBinder.<BindModelAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerArgumentBinder.<BindArgumentsCoreAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

有什么线索吗?

【问题讨论】:

  • 您是否将这个ApplicationContext 注入到某个MVC 模型中?你应该保持你的 MVC 模型没有任何依赖。一个 MVC 模型 == 数据。
  • 不,根据我的理解,我的 ApplicationContext 没有注入任何 MVC 模型。我的模型只有 1 个依赖项,即 System.ComponentModel.DataAnnotations; 他们使用字符串作为数据,使用 int 作为键(ID)
  • 你解决过这个问题吗?我也一样

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


【解决方案1】:

我刚刚解决了一个类似的问题。我的问题是我误解了依赖注入。上下文不会传递给 Controller 方法,而是传递给 Controller 的构造函数。

public class NetworksController : Controller
{
    private readonly ChoirAdminContext db;

    public NetworksController(ApplicationContext context)
    {
        db = context;
    }

    public JsonResult Index()
    {
        return Json(db.Networks);
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2020-11-05
    • 2016-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2019-02-22
    相关资源
    最近更新 更多