问题
I am using .NET Core dependency injection, but when I am trying to get the service in another class, I am getting the 'IServiceProvider.GetService(Type)' cannot be used with type arguments' error.
What does this error means? I understand that a generic type argument is something like this: GenericInterface<>, and the GetService method does not take the GenericInterface<> as an argument.
Why am I getting this error and how do I solve it?
The interface
public interface IService
{
void Process();
}
The class implementing the interface
public class Service : BaseService<IConfig, SomType>
{
public Service(
ILogger logger : base(logger)
{
}
...
}
The BaseService class is an abstract class and it implements the IService interface.
public abstract class BaseService<TConfig, TE> : AnotherBaseService, IService where TConfig : IConfig where TE : struct, IConvertible
{
protected BaseService(ILogger logger): base(logger)
{
}
...
}
The AnotherBaseService
public abstract class BaseService
{
protected readonly ILogger Logger;
protected BaseService(ILogger logger)
{
Logger = logger;
}
...
}
How I registered them.
serviceCollection.AddScoped<IService, Service>();
How I am getting the service I need.
var incoming = serviceProvider.GetService<IService>();
NB: I am just getting started with dependency injection, .NET Core and do not know everything about DI just yet. Your answers would be of great help.
回答1:
The generic GetService< T> method is an extension method. This means you need to have a :
using Microsoft.Extensions.DependencyInjection;
to allow the compiler to find it.
This method is only meant for optional services. It will return null
if the object can't be constructed, either because the type wasn't registered or because some of its dependencies are missing.
GetRequiredService should be used when an application can't work unless a service is available. If an instance can't be created, it will throw an InvalidOperationException.
When that exception is thrown, the full exception text will be a huge help in finding the actual problem. Exceptions thrown in constructors can appear in the Exception.InnerException property. The sequence of calls that ended up in an exception being thrown will appear in the StackTrace property. Calling Exception.ToString() will return a string that contains all of that information for the current exception and any inner exceptions.
回答2:
It means your compiler only has knowledge of the method that takes a type.
You could call
var incoming = serviceProvider.GetService(typeof(IService));
or you could add a
using Microsoft.Extensions.DependencyInjection;
to make sure your compiler knows the extension method that lets you specify your type as a generic parameter. This might need the package Microsoft.Extensions.DependencyInjection.Abstractions
to be installed.
来源:https://stackoverflow.com/questions/54216939/the-non-generic-method-iserviceprovider-getservicetype-cannot-be-used-with-t