You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When i debug, it gets through all the API startup logic with no errors, then when it goes to execute the line in the test below, if fails.
when i tries to execute the test, it throws the error.
Why is it looking for WebApplication and failing? I tried adding to services collection, but that collection is read only.
System.InvalidOperationException : Could not resolve a service of type 'Microsoft.AspNetCore.Builder.WebApplication' for the parameter 'app' of method 'Configure' on type 'Vitech.Sidekick.DiagramAPI.Startup'.
---- System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Builder.WebApplication' has been registered.
Function Main of API i am testing:
Loads no issue.
namespace Vitech.Sidekick.DiagramAPI
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var configuration = builder.Configuration;
var start = new Startup(builder);
start.ConfigureServices(builder.Services);
start.Configure(start.Application);
start.Application.Run();
}
}
}
Here is my test. does nothing.
[Fact]
public void TestMVC()
{
MyController.Instance(); // will get above exception once i get here.
}
TestStartup.cs
namespace MyApp.Tests
{
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Vitech.Sidekick.DiagramAPI;
using Microsoft.Extensions.Configuration;
using Moq;
using Vitech.Sidekick.DiagramAPI.Controllers;
using Vitech.Sidekick.DiagramData;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using MyTested.AspNetCore.Mvc;
public class TestStartup : Startup
{
public TestStartup() : base(WebApplication.CreateBuilder())
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
}
public void ConfigureTestServices(IServiceCollection services)
{
base.ConfigureServices(Builder.Services);
}
public override void Configure(WebApplication app)
{
base.Configure(app);
}
/// <summary>
/// Create test db.
/// </summary>
/// <param name="builder"></param>
protected override void AddDbContext(WebApplicationBuilder builder)
{
//var optionsBuilder = new DbContextOptionsBuilder<DiagramDbContext>();
builder.Services.AddDbContext<DiagramDbContext>(o =>
{
var connectionString = builder.Configuration.GetConnectionString(nameof(DiagramDbContext));
Console.WriteLine($"ConnectionString = {connectionString}");
o.UseInMemoryDatabase("SideKickDb");
});
}
}
}
API Startup:
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System;
using System.Net;
using System.Text.Json.Serialization;
using Vitech.Sidekick.DiagramData;
namespace Vitech.Sidekick.DiagramAPI
{
///
/// Configures OWIN at startup.
///
public class Startup
{
public Startup(): this(WebApplication.CreateBuilder())
{
}
public Startup( WebApplicationBuilder builder)
{
Configuration = builder.Configuration;
Builder = builder;
}
protected WebApplicationBuilder Builder { get; set; }
public WebApplication Application { get; set; }
public IConfiguration Configuration { get; }
public virtual void ConfigureServices(IServiceCollection services)
{
// var services = builder.Services;
services.AddSingleton(Configuration);
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddAuthorization();
services.AddAuthentication();
var section = Configuration.GetSection("ServiceSettings");
ServiceSettings? settings = section.Get<ServiceSettings?>();
if (settings != null)
{
services.AddSingleton(settings);
}
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "DiagramAPI",
Description = "DiagramAPI",
});
var securitySchema = new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
};
c.AddSecurityDefinition("Bearer", securitySchema);
var securityRequirement = new OpenApiSecurityRequirement();
securityRequirement.Add(securitySchema, new[] { "Bearer" });
c.AddSecurityRequirement(securityRequirement);
});
services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
services.AddTransient<SessionDataProvider>();
CreateDbContext(Builder);
Application = Builder.Build();
}
private void CreateDbContext(WebApplicationBuilder builder)
{
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var currentDir = Directory.GetCurrentDirectory();
Console.WriteLine(currentDir);
// Build config
//string basePath = Path.Combine(currentDir, @"..\Vitech.Sidekick.DiagramAPI");
// Console.WriteLine(basePath);
builder.Configuration
.SetBasePath(currentDir)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables();
// Auto Mapper Configurations
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new Mapper());
});
IMapper mapper = mapperConfig.CreateMapper();
builder.Services.AddSingleton(mapper);
// Add Db
AddDbContext(builder);
}
protected virtual void AddDbContext(WebApplicationBuilder builder)
{
//var optionsBuilder = new DbContextOptionsBuilder<DiagramDbContext>();
builder.Services.AddDbContext<DiagramDbContext>(o =>
{
var connectionString = builder.Configuration.GetConnectionString(nameof(DiagramDbContext));
Console.WriteLine($"ConnectionString = {connectionString}");
o.UseSqlServer(connectionString);
});
}
public virtual void Configure(WebApplication app)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(opts =>
{
opts.EnablePersistAuthorization();
}).UseAuthentication();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
CreateDbIfNotExists(app);
}
private void CreateDbIfNotExists(IHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DiagramDbContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}
}
}
}
The text was updated successfully, but these errors were encountered:
When i debug, it gets through all the API startup logic with no errors, then when it goes to execute the line in the test below, if fails.
when i tries to execute the test, it throws the error.
Why is it looking for WebApplication and failing? I tried adding to services collection, but that collection is read only.
System.InvalidOperationException : Could not resolve a service of type 'Microsoft.AspNetCore.Builder.WebApplication' for the parameter 'app' of method 'Configure' on type 'Vitech.Sidekick.DiagramAPI.Startup'.
---- System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Builder.WebApplication' has been registered.
Function Main of API i am testing:
Loads no issue.
namespace Vitech.Sidekick.DiagramAPI
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
}
Here is my test. does nothing.
[Fact]
public void TestMVC()
{
MyController.Instance(); // will get above exception once i get here.
}
TestStartup.cs
namespace MyApp.Tests
{
}
API Startup:
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System;
using System.Net;
using System.Text.Json.Serialization;
using Vitech.Sidekick.DiagramData;
namespace Vitech.Sidekick.DiagramAPI
{
///
/// Configures OWIN at startup.
///
public class Startup
{
// var services = builder.Services;
services.AddSingleton(Configuration);
}
The text was updated successfully, but these errors were encountered: