无法解析ASP.NET Core DI类型的服务

时间:2018-05-29 15:11:06

标签: .net dependency-injection .net-core .net-standard

在调用使用它的Controller时,看到一些奇怪的情况,我在.NET Standard 2.0 CL服务中遇到DI错误。

控制器

[Route("api/[controller]")]
public class VideoController : Controller
{
    private readonly IVideoService _videoService;

    public VideoController(IVideoService videoService)
    {
        _videoService = videoService;
    }
    [HttpGet("[action]")]
    public List<Video> GetVideos()
    {
        return _videoService.GetVideos().Result.ToList();
    }
}

CL中的服务

public class VideoService : IVideoService
{
    private readonly ILogger log;
    private readonly ConfigWrapper config;

    private readonly IAzureMediaServicesHelpers amsHelpers;
    private readonly IStorageHelpers storageHelpers;

    public VideoService(ILogger logger, ConfigWrapper _config, IAzureMediaServicesHelpers _amsHelper, IStorageHelpers _storageHelper)
    {
        log = logger;
        config = _config;
        amsHelpers = _amsHelper;
        storageHelpers = _storageHelper;
    }

在.NET Core项目中启动

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IStorageHelpers, StorageHelpers>();
    services.AddTransient<IAzureMediaServicesHelpers, AzureMediaServicesHelpers>();
    services.AddTransient<IVideoService, VideoService>();
    services.AddMvc();
}

我得到的错误是典型的中间件异常

  

尝试激活Demo.Shared.VideoService时,无法解析“Microsoft.Extensions.Logging.ILogger”类型的服务。

我在这里没有使用Logger,因为这个CL也被不支持Logger的Azure功能使用。我想我错过了一些简单的东西。

2 个答案:

答案 0 :(得分:0)

按预期工作。创建一个与ILogger匹配的课程,该课程不做任何事情。并注册它。有一天,您可能希望用真实的记录方法替换该假人。

From the DLL: Microsoft.Extensions.Logging


Class MyLovelyClass
    Implements Microsoft.Extensions.Logging.ILogger

    Public Sub Log(Of TState)(logLevel As LogLevel, eventId As EventId, state As TState, exception As Exception, formatter As Func(Of TState, Exception, String)) Implements ILogger.Log
        Throw New NotImplementedException()
    End Sub

    Public Function IsEnabled(logLevel As LogLevel) As Boolean Implements ILogger.IsEnabled
        Throw New NotImplementedException()
    End Function

    Public Function BeginScope(Of TState)(state As TState) As IDisposable Implements ILogger.BeginScope
        Throw New NotImplementedException()
    End Function
End Class

答案 1 :(得分:0)

只需使用ILogger<VideoService>代替ILogger。尝试像这样更改VideoService构造函数:

public VideoService(ILogger<VideoService> logger, ConfigWrapper _config, IAzureMediaServicesHelpers _amsHelper, IStorageHelpers _storageHelper)