无法解析Azure Microservice中的类型服务

问题描述 投票:2回答:1

这是我第一次尝试使用Azure Service Fabric和.Net Core创建微服务

在调试模式下它工作正常,我可以使用Postman命中API端点。但是,当我将Service Fabric应用程序发布到Service Fabric Local Cluster(单节点)后尝试命中相同的端点时,它会抛出以下异常

尝试激活“UrlShortener.WebService.Controllers.UrlShortenerController”时,无法解析“UrlShortener.Services.Contracts.IUrlService”类型的服务。

我不确定这里缺少什么。

这是我的代码片段

调节器

 public class UrlShortenerController : ControllerBase
 {
        private readonly IUrlService _urlService;

        public UrlShortenerController(IUrlService urlService)
        {
            _urlService = urlService;
        }
 }

服务

public class UrlService : EntityService<Url>, IUrlService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IUrlRepository _repo;
    private readonly IOptions<ShortenUrlConfig> _config;
    public UrlService(IUnitOfWork unitOfWork, IUrlRepository repo, IOptions<ShortenUrlConfig> config)
        : base(unitOfWork, repo)
    {
        _unitOfWork = unitOfWork;
        _repo       = repo;
        _config     = config;
    }

}

服务扩展

public static IServiceCollection RegisterCustomServices(this IServiceCollection services)
        {
            services.AddScoped<IUrlService, UrlService>();

            return services;
        }

        public static IServiceCollection RegisterRepositories(this IServiceCollection services)
        {
            services.AddScoped<IUrlRepository, UrlRepository>();
            return services;
        }

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.RegisterCustomContracts();
            services.RegisterCustomServices();
            services.RegisterRepositories();


            // configure the system messages
            services.Configure<ShortenUrlConfig>(Configuration.GetSection("ShortenUrlConfig"));

            services.AddEntityFramework(Configuration.GetConnectionString("TestDBContext"));
        }
c# azure asp.net-core microservices azure-service-fabric
1个回答
0
投票

引发异常是因为urlService未在控制器构造函数UrlShortenerController(IUrlService urlService)中解析:

我建议在注册这样的服务后调用services.AddMvc()方法:

public void ConfigureServices(IServiceCollection services)
{
     services.RegisterCustomContracts();
     services.RegisterCustomServices();
     services.RegisterRepositories();
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

     // configure the system messages
     services.Configure<ShortenUrlConfig>(Configuration.GetSection("ShortenUrlConfig"));
     services.AddEntityFramework(Configuration.GetConnectionString("TestDBContext"));
}    
© www.soinside.com 2019 - 2024. All rights reserved.