在启动文件上注册对象和接口时出现问题 更具体地说,在 ConfigureServices 方法中,应用不会执行



好吧,我已经创建了一个应用程序来从头开始在ASP网络核心3.1上启动,我创建了一个API应用程序,并且我已经创建了一些层来更好地控制我的应用程序,但是,当我使用其接口创建对象并以这种方式在启动文件中注册它们时:

services.AddScoped<IMySpaceService, MySpaceService>();

我在运行应用程序时收到此错误:

未处理的异常。System.AggregateException:某些服务无法构造(验证服务描述符"服务类型:MySpaceService.Services.Interfaces.IMySpaceService Lifetime: Scoped ImplementationType:

这是我的代码:

public class MySpaceService: IMySpaceService
{
private IMySpaceRepository _mySpaceRepository;
public MySpaceService(IMySpaceRepository mySpaceRepository)
{
_mySpaceRepository = mySpaceRepository;
}
public IList<MySpaceDto> getSpaces()
{
List<MySpaceDto> spaces = new List<MySpaceDto>();
var data = _mySpaceRepository.getSpaces();
foreach (var item in data)
{
SpaceDto spaceDto = new SpaceDto();
spaceDto.Identification = item.Identification;
spaceDto.Name = item.Name;
spaces.Add(spaceDto);
}
return spaces;
}
}

我的启动代码:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IMySpaceService, MySpaceService>();
services.AddScoped<IMySpaceRepository, MySpaceRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

有什么想法吗?

您的MySpaceService只有一个带有参数IMySpaceRepository的构造函数。您还需要注册存储库:

services.AddScoped<IMySpaceRepository, MySpaceRepository>();
services.AddScoped<IMySpaceService, MySpaceService>();

好吧,问题肯定是我还没有注册依赖项,但是,我没有注册的依赖项是"Dbcontext",我从构造函数上的存储库类调用它。因此,我不得不说您的评论帮助我解决了我的问题,因为最后,这是未注册的依赖项问题。

我必须在启动文件上执行此操作:

services.AddDbContext<ExampleContext>(
options => options.UseMySql("Server=localhost;port=3306;Database=exampleDB;User=UserRegistered;Password=*******", mySqlOptions => mySqlOptions
.ServerVersion(new ServerVersion(new Version(8, 0, 18), ServerType.MySql))));

最新更新