这是我第一次尝试使用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;
}
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"));
}
引发异常是因为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"));
}