首页 > 解决方案 > 为什么我的上下文在我可以使用之前就被处理掉了?

问题描述

HotChocolate在 .Net 5 项目中使用 GraphQL 库实现了一个非常简单的查询。我一直在关注 HotChocolate GitHub 存储库中的教程系列,但在我的项目中,我不希望 GraphQL 直接访问上下文,而是希望它访问通过上下文管理数据库访问的存储库。

我在这个项目中与 GraphQL 一起构建了一些 REST 端点,并且这个存储库模式在那里正常工作。但是,当我从 GraphQL 调用这些存储库方法时,上下文会在存储库方法使用它之前被释放。

我猜 HotChocolate 使用上下文的方式导致它比我预期的更早被处理,但我无法弄清楚它何时/何​​处被处理以及如何防止它被处理,以便我的存储库方法可以工作。

内容存储库.cs

namespace BLL.Repository
{
    public class ContentRepository : IRepository<Content>
    {
        private readonly CmsContext _dbContext;

        public ContentRepository(CmsContext dbContext)
        {
            _dbContext = dbContext;
        }

        public virtual List<Content> GetContent()
        {
            return _dbContext.Content.ToList();
        }
    }
}

查询.cs

namespace Web.GraphQL
{
    public class Query
    {
        private readonly IContentRepository _contentRepository;

        public Query(IContentRepository contentRepository)
        {
            _contentRepository = contentRepository;
        }
        
        public List<Content> GetContent()
        {
            return _contentRepository.GetContent() as List<Content>;
        }
    }
}

启动.cs

namespace Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddControllers().AddNewtonsoftJson();
            
            services.AddDbContext<CmsContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection"))));
            
            services
                .AddGraphQLServer()
                .ModifyRequestOptions(options => options.IncludeExceptionDetails = true)
                .AddQueryType<Query>();

            services.AddScoped<IRepository<Content>, ContentRepository>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

            app.UseHttpsRedirection();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "/{controller}/{action}",
                    new {controller = "Default", action = "Index"});
            });

            app.UseEndpoints(endpoints => endpoints.MapGraphQL());

            app.UseGraphQLVoyager(new VoyagerOptions
            {
                GraphQLEndPoint = "/graphql"
            }, "/graphql-voyager");
        }
    }
}

在调试和单步执行代码时,一旦到达其中的GetContent方法,ContentRepository.cs就会抛出一个ObjectDisposedException.

我需要做些什么来确保从 GraphQL 查询调用时CmsContext仍然可以使用它?ContentRepository

标签: c#asp.net-corehotchocolate

解决方案


您只能将构造函数注入与 HotChocolate v11一起使用:

services
    .AddScoped<IUserRepository, UserRepository>()
    .AddScoped<Query>()
    .AddGraphQLServer()
    .AddQueryType<Query>()

public class Query
{
    public Query(IUserRepository repository)
    {

    }

    // code omitted for brevity
}

如果您使用的是 HotChocolate v10,则需要使用带有属性的参数注入:[Service]

public class Query
{
    public string Bar(ISchema schema, [Service]MyCustomService service)
    {
        return "foo";
    }
}

参考


推荐阅读