C# 类型'没有构造函数;MyProject.Response';可以使用服务容器中的服务和默认值进行实例化

C# 类型'没有构造函数;MyProject.Response';可以使用服务容器中的服务和默认值进行实例化,c#,dependency-injection,c#-8.0,asp.net-core-3.1,C#,Dependency Injection,C# 8.0,Asp.net Core 3.1,我正在使用asp.net core 3.1项目模板开发web API。没有编译错误 下面是我的代码详细信息: Program.cs public class Program { public static void Main(string[] args) { // Use the W3C Trace Context format to propagate distributed trace identifiers. // See https://d

我正在使用asp.net core 3.1项目模板开发web API。没有编译错误

下面是我的代码详细信息:

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        // Use the W3C Trace Context format to propagate distributed trace identifiers.
        // See https://devblogs.microsoft.com/aspnet/improvements-in-net-core-3-0-for-troubleshooting-and-monitoring-distributed-apps/
        Activity.DefaultIdFormat = ActivityIdFormat.W3C;
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
public class Startup
{
    private readonly IConfiguration configuration;
    private readonly IWebHostEnvironment webHostEnvironment;
    /// <summary>
    /// Initializes a new instance of the <see cref = "Startup"/> class.
    /// </summary>
    /// <param name = "configuration">The application configuration, where key value pair settings are stored. See
    /// http://docs.asp.net/en/latest/fundamentals/configuration.html</param>
    /// <param name = "webHostEnvironment">The environment the application is running under. This can be Development,
    /// Staging or Production by default. See http://docs.asp.net/en/latest/fundamentals/environments.html</param>
    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        this.configuration = configuration;
        this.webHostEnvironment = webHostEnvironment;
    }

    /// <summary>
    /// Configures the services to add to the ASP.NET Core Injection of Control (IoC) container. This method gets
    /// called by the ASP.NET runtime. See
    /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
    /// </summary>
    public virtual void ConfigureServices(IServiceCollection services) => 
        services
        .AddCosmosDBConfiguration(configuration)
        .AddAutoMapperConfiguration()
        .AddCustomResponseCompression(configuration)
        .AddCustomCors()
        .AddCustomOptions(configuration)
        .AddHttpContextAccessor()
        .AddCustomRouting()
        .AddCustomStrictTransportSecurity()
        .AddCustomHealthChecks()
        .AddServerTiming()
        .AddControllers()
           .AddCustomJsonOptions(webHostEnvironment)
           .AddCustomMvcOptions(configuration)
        .Services
        .AddCustomGraphQL(configuration, webHostEnvironment)
        .AddGraphQLResolvers()
        .AddGraphQLResponse()
        .AddProjectRepositories()
        .AddProjectSchemas();

    /// <summary>
    /// Configures the application and HTTP request pipeline. Configure is called after ConfigureServices is
    /// called by the ASP.NET runtime.
    /// </summary>
    public virtual void Configure(IApplicationBuilder application) =>
        application
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseServerTiming())
        .UseForwardedHeaders()
        .UseResponseCompression()
        .UseFetchLocaleMiddleware()
        .UseIf(
                !this.webHostEnvironment.IsDevelopment(),
                x => x.UseHsts())
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseDeveloperExceptionPage())
        .UseRouting()
            .UseCors(CorsPolicyName.AllowAny)
        .UseEndpoints(
                builder =>
                {
                    builder
                        .MapHealthChecks("/status")
                        .RequireCors(CorsPolicyName.AllowAny);
                    builder
                        .MapHealthChecks("/status/self", new HealthCheckOptions() { Predicate = _ => false })
                        .RequireCors(CorsPolicyName.AllowAny);
                })
        .UseWebSockets()
            // Use the GraphQL subscriptions in the specified schema and make them available at /graphql.
            .UseGraphQLWebSockets<MainSchema>()
            // Use the specified GraphQL schema and make them available at /graphql.
            .UseGraphQL<MainSchema>()
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x
                    // Add the GraphQL Playground UI to try out the GraphQL API at /.
                    .UseGraphQLPlayground(new GraphQLPlaygroundOptions() { Path = "/" })
                    // Add the GraphQL Voyager UI to let you navigate your GraphQL API as a spider graph at /voyager.
                    .UseGraphQLVoyager(new GraphQLVoyagerOptions() { Path = "/voyager" }));
}
public class Response
{
    public object Data { get; set; }

    public string StatusCode { get; set; }

    public string ErrorMessage { get; set; }

    public Response(object data)
    {
        StatusCode = "Success";
        Data = data;
    }

    public Response(string statusCode, string errorMessage)
    {
        StatusCode = statusCode;
        ErrorMessage = errorMessage;
    }
}
namespace MyProject
{
    public static class ProjectServiceCollectionExtensions
    {
        public static IServiceCollection AddGraphQLResponse(this IServiceCollection services) => services.AddScoped<Response>();
    }
}
public class Resolver
{
    public Response Response(object data)
    {
        return new Response(data);
    }

    public Response Error(GraphQLError error)
    {
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response AccessDeniedError()
    {
        var error = new AccessDeniedError();
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response NotFoundError(string id)
    {
        var error = new NotFoundError(id);
        return new Response(error.StatusCode, error.ErrorMessage);
    }
}
using Author.Core.Framework.Utilities;
using Author.Query.New.API.GraphQL.Types;
using Author.Query.Persistence.DTO;
using Author.Query.Persistence.Interfaces;
using GraphQL.DataLoader;
using GraphQL.Types;
using Microsoft.AspNetCore.Http;
using System;

namespace MyProject.GraphQL.Resolvers
{
    public class CountriesResolver : Resolver, ICountriesResolver
    {
        private readonly ICountryService _countryService;
        private readonly IHttpContextAccessor _accessor;
        private readonly IUtilityService _utilityService;
        private readonly IDataLoaderContextAccessor _dataLoaderContextAccessor;
        public CountriesResolver(ICountryService countryService, IHttpContextAccessor accessor, IUtilityService utilityService, IDataLoaderContextAccessor dataLoaderContextAccessor)
        {
            _countryService = countryService ?? throw new ArgumentNullException(nameof(countryService));
            _accessor = accessor;
            _utilityService = utilityService ?? throw new ArgumentNullException(nameof(utilityService));
            _dataLoaderContextAccessor = dataLoaderContextAccessor;
        }

        public void Resolve(GraphQLQuery graphQLQuery)
        {
            var language = _accessor.HttpContext.Items["language"] as LanguageDTO;
            graphQLQuery.FieldAsync<ResponseGraphType<CountryResultType>>("countriesresponse", resolve: async context =>
            {
                if (language != null)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetAllCountries", () => _countryService.GetAllCountriesAsync(language));
                    var list = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(list);
                }

                return null;
            }

            , description: "All Countries data");
            graphQLQuery.FieldAsync<ResponseGraphType<CountryType>>("country", arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IntGraphType>>{Name = "countryId", Description = "id of the country"}), resolve: async context =>
            {
                var countryId = context.GetArgument<int>("countryId");
                if (language != null && countryId > 0)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetCountry", () => _countryService.GetCountryAsync(language, countryId));
                    var countryDetails = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(countryDetails);
                }

                return null;
            }

            );
        }
    }
}
Startup.cs的
ConfigureServices
中提到的所有依赖项都可用。在验证API时,我遇到一个运行时错误,如下所述:

无法使用服务容器中的服务和默认值实例化类型“MyProject.Response”的构造函数

下面是响应类所需的依赖项设置,如下所述:

projectservicecolectionextensions.cs

public class Program
{
    public static void Main(string[] args)
    {
        // Use the W3C Trace Context format to propagate distributed trace identifiers.
        // See https://devblogs.microsoft.com/aspnet/improvements-in-net-core-3-0-for-troubleshooting-and-monitoring-distributed-apps/
        Activity.DefaultIdFormat = ActivityIdFormat.W3C;
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
public class Startup
{
    private readonly IConfiguration configuration;
    private readonly IWebHostEnvironment webHostEnvironment;
    /// <summary>
    /// Initializes a new instance of the <see cref = "Startup"/> class.
    /// </summary>
    /// <param name = "configuration">The application configuration, where key value pair settings are stored. See
    /// http://docs.asp.net/en/latest/fundamentals/configuration.html</param>
    /// <param name = "webHostEnvironment">The environment the application is running under. This can be Development,
    /// Staging or Production by default. See http://docs.asp.net/en/latest/fundamentals/environments.html</param>
    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        this.configuration = configuration;
        this.webHostEnvironment = webHostEnvironment;
    }

    /// <summary>
    /// Configures the services to add to the ASP.NET Core Injection of Control (IoC) container. This method gets
    /// called by the ASP.NET runtime. See
    /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
    /// </summary>
    public virtual void ConfigureServices(IServiceCollection services) => 
        services
        .AddCosmosDBConfiguration(configuration)
        .AddAutoMapperConfiguration()
        .AddCustomResponseCompression(configuration)
        .AddCustomCors()
        .AddCustomOptions(configuration)
        .AddHttpContextAccessor()
        .AddCustomRouting()
        .AddCustomStrictTransportSecurity()
        .AddCustomHealthChecks()
        .AddServerTiming()
        .AddControllers()
           .AddCustomJsonOptions(webHostEnvironment)
           .AddCustomMvcOptions(configuration)
        .Services
        .AddCustomGraphQL(configuration, webHostEnvironment)
        .AddGraphQLResolvers()
        .AddGraphQLResponse()
        .AddProjectRepositories()
        .AddProjectSchemas();

    /// <summary>
    /// Configures the application and HTTP request pipeline. Configure is called after ConfigureServices is
    /// called by the ASP.NET runtime.
    /// </summary>
    public virtual void Configure(IApplicationBuilder application) =>
        application
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseServerTiming())
        .UseForwardedHeaders()
        .UseResponseCompression()
        .UseFetchLocaleMiddleware()
        .UseIf(
                !this.webHostEnvironment.IsDevelopment(),
                x => x.UseHsts())
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseDeveloperExceptionPage())
        .UseRouting()
            .UseCors(CorsPolicyName.AllowAny)
        .UseEndpoints(
                builder =>
                {
                    builder
                        .MapHealthChecks("/status")
                        .RequireCors(CorsPolicyName.AllowAny);
                    builder
                        .MapHealthChecks("/status/self", new HealthCheckOptions() { Predicate = _ => false })
                        .RequireCors(CorsPolicyName.AllowAny);
                })
        .UseWebSockets()
            // Use the GraphQL subscriptions in the specified schema and make them available at /graphql.
            .UseGraphQLWebSockets<MainSchema>()
            // Use the specified GraphQL schema and make them available at /graphql.
            .UseGraphQL<MainSchema>()
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x
                    // Add the GraphQL Playground UI to try out the GraphQL API at /.
                    .UseGraphQLPlayground(new GraphQLPlaygroundOptions() { Path = "/" })
                    // Add the GraphQL Voyager UI to let you navigate your GraphQL API as a spider graph at /voyager.
                    .UseGraphQLVoyager(new GraphQLVoyagerOptions() { Path = "/voyager" }));
}
public class Response
{
    public object Data { get; set; }

    public string StatusCode { get; set; }

    public string ErrorMessage { get; set; }

    public Response(object data)
    {
        StatusCode = "Success";
        Data = data;
    }

    public Response(string statusCode, string errorMessage)
    {
        StatusCode = statusCode;
        ErrorMessage = errorMessage;
    }
}
namespace MyProject
{
    public static class ProjectServiceCollectionExtensions
    {
        public static IServiceCollection AddGraphQLResponse(this IServiceCollection services) => services.AddScoped<Response>();
    }
}
public class Resolver
{
    public Response Response(object data)
    {
        return new Response(data);
    }

    public Response Error(GraphQLError error)
    {
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response AccessDeniedError()
    {
        var error = new AccessDeniedError();
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response NotFoundError(string id)
    {
        var error = new NotFoundError(id);
        return new Response(error.StatusCode, error.ErrorMessage);
    }
}
using Author.Core.Framework.Utilities;
using Author.Query.New.API.GraphQL.Types;
using Author.Query.Persistence.DTO;
using Author.Query.Persistence.Interfaces;
using GraphQL.DataLoader;
using GraphQL.Types;
using Microsoft.AspNetCore.Http;
using System;

namespace MyProject.GraphQL.Resolvers
{
    public class CountriesResolver : Resolver, ICountriesResolver
    {
        private readonly ICountryService _countryService;
        private readonly IHttpContextAccessor _accessor;
        private readonly IUtilityService _utilityService;
        private readonly IDataLoaderContextAccessor _dataLoaderContextAccessor;
        public CountriesResolver(ICountryService countryService, IHttpContextAccessor accessor, IUtilityService utilityService, IDataLoaderContextAccessor dataLoaderContextAccessor)
        {
            _countryService = countryService ?? throw new ArgumentNullException(nameof(countryService));
            _accessor = accessor;
            _utilityService = utilityService ?? throw new ArgumentNullException(nameof(utilityService));
            _dataLoaderContextAccessor = dataLoaderContextAccessor;
        }

        public void Resolve(GraphQLQuery graphQLQuery)
        {
            var language = _accessor.HttpContext.Items["language"] as LanguageDTO;
            graphQLQuery.FieldAsync<ResponseGraphType<CountryResultType>>("countriesresponse", resolve: async context =>
            {
                if (language != null)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetAllCountries", () => _countryService.GetAllCountriesAsync(language));
                    var list = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(list);
                }

                return null;
            }

            , description: "All Countries data");
            graphQLQuery.FieldAsync<ResponseGraphType<CountryType>>("country", arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IntGraphType>>{Name = "countryId", Description = "id of the country"}), resolve: async context =>
            {
                var countryId = context.GetArgument<int>("countryId");
                if (language != null && countryId > 0)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetCountry", () => _countryService.GetCountryAsync(language, countryId));
                    var countryDetails = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(countryDetails);
                }

                return null;
            }

            );
        }
    }
}
CountriesResolver.cs

public class Program
{
    public static void Main(string[] args)
    {
        // Use the W3C Trace Context format to propagate distributed trace identifiers.
        // See https://devblogs.microsoft.com/aspnet/improvements-in-net-core-3-0-for-troubleshooting-and-monitoring-distributed-apps/
        Activity.DefaultIdFormat = ActivityIdFormat.W3C;
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
public class Startup
{
    private readonly IConfiguration configuration;
    private readonly IWebHostEnvironment webHostEnvironment;
    /// <summary>
    /// Initializes a new instance of the <see cref = "Startup"/> class.
    /// </summary>
    /// <param name = "configuration">The application configuration, where key value pair settings are stored. See
    /// http://docs.asp.net/en/latest/fundamentals/configuration.html</param>
    /// <param name = "webHostEnvironment">The environment the application is running under. This can be Development,
    /// Staging or Production by default. See http://docs.asp.net/en/latest/fundamentals/environments.html</param>
    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        this.configuration = configuration;
        this.webHostEnvironment = webHostEnvironment;
    }

    /// <summary>
    /// Configures the services to add to the ASP.NET Core Injection of Control (IoC) container. This method gets
    /// called by the ASP.NET runtime. See
    /// http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx
    /// </summary>
    public virtual void ConfigureServices(IServiceCollection services) => 
        services
        .AddCosmosDBConfiguration(configuration)
        .AddAutoMapperConfiguration()
        .AddCustomResponseCompression(configuration)
        .AddCustomCors()
        .AddCustomOptions(configuration)
        .AddHttpContextAccessor()
        .AddCustomRouting()
        .AddCustomStrictTransportSecurity()
        .AddCustomHealthChecks()
        .AddServerTiming()
        .AddControllers()
           .AddCustomJsonOptions(webHostEnvironment)
           .AddCustomMvcOptions(configuration)
        .Services
        .AddCustomGraphQL(configuration, webHostEnvironment)
        .AddGraphQLResolvers()
        .AddGraphQLResponse()
        .AddProjectRepositories()
        .AddProjectSchemas();

    /// <summary>
    /// Configures the application and HTTP request pipeline. Configure is called after ConfigureServices is
    /// called by the ASP.NET runtime.
    /// </summary>
    public virtual void Configure(IApplicationBuilder application) =>
        application
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseServerTiming())
        .UseForwardedHeaders()
        .UseResponseCompression()
        .UseFetchLocaleMiddleware()
        .UseIf(
                !this.webHostEnvironment.IsDevelopment(),
                x => x.UseHsts())
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x.UseDeveloperExceptionPage())
        .UseRouting()
            .UseCors(CorsPolicyName.AllowAny)
        .UseEndpoints(
                builder =>
                {
                    builder
                        .MapHealthChecks("/status")
                        .RequireCors(CorsPolicyName.AllowAny);
                    builder
                        .MapHealthChecks("/status/self", new HealthCheckOptions() { Predicate = _ => false })
                        .RequireCors(CorsPolicyName.AllowAny);
                })
        .UseWebSockets()
            // Use the GraphQL subscriptions in the specified schema and make them available at /graphql.
            .UseGraphQLWebSockets<MainSchema>()
            // Use the specified GraphQL schema and make them available at /graphql.
            .UseGraphQL<MainSchema>()
            .UseIf(
                this.webHostEnvironment.IsDevelopment(),
                x => x
                    // Add the GraphQL Playground UI to try out the GraphQL API at /.
                    .UseGraphQLPlayground(new GraphQLPlaygroundOptions() { Path = "/" })
                    // Add the GraphQL Voyager UI to let you navigate your GraphQL API as a spider graph at /voyager.
                    .UseGraphQLVoyager(new GraphQLVoyagerOptions() { Path = "/voyager" }));
}
public class Response
{
    public object Data { get; set; }

    public string StatusCode { get; set; }

    public string ErrorMessage { get; set; }

    public Response(object data)
    {
        StatusCode = "Success";
        Data = data;
    }

    public Response(string statusCode, string errorMessage)
    {
        StatusCode = statusCode;
        ErrorMessage = errorMessage;
    }
}
namespace MyProject
{
    public static class ProjectServiceCollectionExtensions
    {
        public static IServiceCollection AddGraphQLResponse(this IServiceCollection services) => services.AddScoped<Response>();
    }
}
public class Resolver
{
    public Response Response(object data)
    {
        return new Response(data);
    }

    public Response Error(GraphQLError error)
    {
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response AccessDeniedError()
    {
        var error = new AccessDeniedError();
        return new Response(error.StatusCode, error.ErrorMessage);
    }

    public Response NotFoundError(string id)
    {
        var error = new NotFoundError(id);
        return new Response(error.StatusCode, error.ErrorMessage);
    }
}
using Author.Core.Framework.Utilities;
using Author.Query.New.API.GraphQL.Types;
using Author.Query.Persistence.DTO;
using Author.Query.Persistence.Interfaces;
using GraphQL.DataLoader;
using GraphQL.Types;
using Microsoft.AspNetCore.Http;
using System;

namespace MyProject.GraphQL.Resolvers
{
    public class CountriesResolver : Resolver, ICountriesResolver
    {
        private readonly ICountryService _countryService;
        private readonly IHttpContextAccessor _accessor;
        private readonly IUtilityService _utilityService;
        private readonly IDataLoaderContextAccessor _dataLoaderContextAccessor;
        public CountriesResolver(ICountryService countryService, IHttpContextAccessor accessor, IUtilityService utilityService, IDataLoaderContextAccessor dataLoaderContextAccessor)
        {
            _countryService = countryService ?? throw new ArgumentNullException(nameof(countryService));
            _accessor = accessor;
            _utilityService = utilityService ?? throw new ArgumentNullException(nameof(utilityService));
            _dataLoaderContextAccessor = dataLoaderContextAccessor;
        }

        public void Resolve(GraphQLQuery graphQLQuery)
        {
            var language = _accessor.HttpContext.Items["language"] as LanguageDTO;
            graphQLQuery.FieldAsync<ResponseGraphType<CountryResultType>>("countriesresponse", resolve: async context =>
            {
                if (language != null)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetAllCountries", () => _countryService.GetAllCountriesAsync(language));
                    var list = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(list);
                }

                return null;
            }

            , description: "All Countries data");
            graphQLQuery.FieldAsync<ResponseGraphType<CountryType>>("country", arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IntGraphType>>{Name = "countryId", Description = "id of the country"}), resolve: async context =>
            {
                var countryId = context.GetArgument<int>("countryId");
                if (language != null && countryId > 0)
                {
                    var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetCountry", () => _countryService.GetCountryAsync(language, countryId));
                    var countryDetails = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                    return Response(countryDetails);
                }

                return null;
            }

            );
        }
    }
}
使用Author.Core.Framework.Utilities;
使用Author.Query.New.API.GraphQL.Types;
使用Author.Query.Persistence.DTO;
使用Author.Query.Persistence.Interfaces;
使用GraphQL.DataLoader;
使用GraphQL.Types;
使用Microsoft.AspNetCore.Http;
使用制度;
命名空间MyProject.GraphQL.Resolvers
{
公共类CountriesResolver:冲突解决程序,IContriesResolver
{
私人只读ICountryService\u countryService;
专用只读IHttpContextAccessor\u访问器;
专用只读IUtilityService(实用服务);
专用只读IDataLoaderContextAccessor\u dataLoaderContextAccessor;
public CountriesResolver(ICountryService countryService、IHttpContextAccessor访问器、IUtilityService实用程序服务、IDataLoaderContextAccessor dataLoaderContextAccessor)
{
_countryService=countryService??抛出新的ArgumentNullException(nameof(countryService));
_存取器=存取器;
_utilityService=utilityService??抛出新的ArgumentNullException(name of(utilityService));
_dataLoaderContextAccessor=dataLoaderContextAccessor;
}
公共无效解析(GraphQLQuery GraphQLQuery)
{
var language=_accessor.HttpContext.Items[“language”]作为LanguageDTO;
FieldAsync(“countriesresponse”,解析:异步上下文=>
{
if(语言!=null)
{
var loader=_dataLoaderContextAccessor.Context.getOradLoader(“GetAllCountries”,()=>_countryService.GetAllCountriesAsync(语言));
var list=await context.TryAsyncResolve(async=>await loader.LoadAsync());
回复(列表);
}
返回null;
}
,说明:“所有国家数据”);
graphQLQuery.FieldAsync(“国家”,参数:new QueryArguments(new QueryArgument{Name=“countryId”,Description=“国家id”}),resolve:async context=>
{
var countryId=context.GetArgument(“countryId”);
如果(语言!=null&&countryId>0)
{
var loader=\u dataLoaderContextAccessor.Context.getOradLoader(“GetCountry”,()=>\u countryService.GetCountryAsync(语言,countryId));
var countryDetails=await context.TryAsyncResolve(async=>await loader.LoadAsync());
回复(详细信息);
}
返回null;
}
);
}
}
}

任何人都可以根据
解析器如何使用
响应
来帮助我解决这个问题,因为
解析器本质上是一个
响应
工厂,所以
响应
不需要添加到DI/IoC容器中

如果
Response
没有明确地注入到任何地方,那么容器不需要知道它。首先,无需将其添加到容器中

除去

//...
.AddGraphQLResponse() //<--SHOULD BE REMOVED
//...
/。。。

.AddGraphQLResponse()//只是抛出了一个2c,但是如果您在响应中添加了一个公共无参数构造函数会怎么样?谢谢@npinti的响应。我尝试了您的建议,但它不起作用。对于asp.net core 2,同样的设置也可以正常工作。2@santoshkumarpatro我发现很难相信在以前的版本中安装工作正常。容器如何知道选择哪个构造函数以及提供哪些值?你能举例说明这个类是如何使用的吗?@Nkosi:谢谢你的回答。我已经使用Response.cs更新了代码。非常感谢您提供的任何帮助。@santoshkumarpatro Ok基于
Response
如何被
Resolver
使用,我想说
Response
不需要添加到DI/IoC容器中。由于
解析器
本质上是一个
响应
工厂感谢@Nkosi的回复。它帮助我解决了这个问题:)。