asp.net 尝试激活控制器时无法解析服务DbContext

s3fp2yjn  于 2023-01-06  发布在  .NET
关注(0)|答案(2)|浏览(178)

我有自己的DbContext

public class DreamsContext : DbContext
{
    public DbSet<UserAccount> UserAccounts { get; set; }
    public DbSet<DreamPublication> DreamPublications { get; set; }

    public DreamsContext(DbContextOptions<DreamsContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserAccount>().ToTable("dreams_user");
        modelBuilder.Entity<DreamPublication>().ToTable("dream_publications");

        base.OnModelCreating(modelBuilder);
    }
}

其中UserAccountDreamPublication只包含几个带有get和set的字段。
在我的启动中,我为DbContext添加了以下内容:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<Models.DreamsContext>(options =>
                options.UseSqlServer("server = SCAT\\SQLEXPRESS; database = dreams_web; Trusted_Connection=True ; MultipleActiveResultSets = true"));
}

然后我尝试使用DI将DbContext注入到控制器中:

private readonly Models.DreamsContext _context;

public SignUpController (Models.DreamsContext dbContext)
{
    _context = dbContext;
}

但是当我尝试在这个上下文中做一些事情时,我遇到了一个异常:
尝试激活“(My controller)”时无法解析类型“(My DbContext)”的服务
我不知道该怎么办,在MSDN上,他们只是这样做,一切工作
更新。这是在控制台中写入的内容

System.InvalidOperationException: Unable to resolve service for type 'DreamWeb.Models.DreamsContext' while attempting to activate 'DreamWeb.Controllers.SignUpController'.
         at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
         at lambda_method25(Closure , IServiceProvider , Object[] )
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
gwbalxhn

gwbalxhn1#

主要的问题是我试图在Startup类中配置服务,而我使用的是asp.net CORE,所以主要的魔法在program.cs中,我将所有内容都移到program.cs中,所有内容都运行良好。这花了我几天的时间,即使是这样一个小错误
https://learn.microsoft.com/en-us/dotnet/architecture/porting-existing-aspnet-apps/app-startup-differences
据此,startup应该继续在www.example.com内核中工作asp.net,但是我遇到了一些问题

bq3bfh9z

bq3bfh9z2#

我有相同的问题,我解决了添加到项目Program.cs的主文件中的数据库的连接,添加到行var builder后:

// db connection 
builder.Services.AddDbContext<Dbcontexclass>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectionString"));

在appsettings.json中添加:

"ConnectionStrings": {
    "DefaultConnectionString": "SERVER=server;DATABASE=database;User ID=user;PASSWORD=password;"
  }

填充连接字符串Dbcontexclass,它应该可以工作,我将docs链接(https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-7.0&tabs=visual-studio)留给您

相关问题