[英]Net Core - unable to resolve dependency
我正在使用 GraphQL 2.4.0 和 .NET Core 3.1 解決方案和 Microsoft DI。 在突變內部,我需要執行額外的處理(如下面的 MyMutation class 所示)。
我的Schema.cs
看起來像:
public class MySchema : GraphQL.Types.Schema
{
private ISchema _schema { get; set; }
public ISchema GraphQLSchema
{
get
{
return this._schema;
}
}
public MySchema()
{
this._schema = Schema.For(@"
type MyObj{
id: ID
name: String,
type: String,
createdAt: String
}
type Mutation {
objSync(type: String): MyObj
}
type Query {
myobj: MyObj
}
", _ =>
{
_.Types.Include<MyQuery>();
_.Types.Include<MyMutation>();
});
}
}
MyMutation.cs
看起來像:
[GraphQLMetadata("MyMutation")]
public class MyMutation
{
private readonly ISomeType someType;
public MyMutation(ISomeType someType)
{
this.someType= someType;
}
[GraphQLMetadata("objSync")]
public Document SyncObj(string type)
{
byte[] _bytes = null;
_bytes = someType.Process(type).Result;
return new Obj { File = Encoding.UTF8.GetString(_bytes , 0, _bytes .Length) };
}
}
ISomeType
看起來像:
public interface ISomeType
{
Task<byte[]> Process(string type);
}
SomeManager.cs
將是:
public class SomeManager: ISomeType
{
private readonly IConfiguration configuration;
private readonly Func<string, IOtherTypeManager> otherType;
public SomeManager(IConfiguration configuration, Func<string, IOtherTypeManager> otherType)
{
this.configuration = configuration;
this.otherType= otherType;
}
public async Task<byte[]> Process(string type)
{
...
}
}
您可能會注意到,我需要使用 DI 解析 ISomeType。 所以Startup.cs
看起來像:
...
public static void AddServices(this IServiceCollection services)
{
services.AddSingleton<IDependencyResolver>(_ => new FuncDependencyResolver(_.GetRequiredService));
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<IDocumentWriter, DocumentWriter>();
services.AddSingleton<ISomeType, SomeManager>();
...
}
...
當執行程序時,它會拋出以下異常:
Error trying to resolve objSync.
Failed to call Activator.CreateInstance. Type: MyNameSpace.Graphql.MyMutation
No parameterless constructor defined for type 'MyNameSpace.Graphql.MyMutation'.
at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
at System.Activator.CreateInstance(Type type)
at GraphQL.DefaultDependencyResolver.Resolve(Type type)
我需要以不同的方式解析ISomeType
嗎? 請指導。
更新
從MyMutation.cs
ISomeType
了這個問題......但我需要它來調用someType.Process(type).Result
。
MyMutation class 也需要在 DI 容器中注冊。 你能試試這個嗎?
services.AddSingleton<MyMutation>();
services.AddScoped<MyMutation>();
services.AddScoped<ISchema, MySchema>();
基本上我會遵循這個例子: https://github.com/graphql-dotnet/examples/tree/master/src/StarWars
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.