I tried to inject my own service in my api controller, but it throws an InvalidOperationException. It is unable to resolve the service. (.NET 5)
What I am doing wrong?
public class MyController : ControllerBase
{
private readonly MyService _myService;
public ContractsController(MyService service)
{
myService = service;
}
[HttpGet("{id}")]
public Item GetItemById(string id)
{
return _myService.getContract(id);
}
}
This is my Startup file:
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.AddSwaggerGen(c =>
{
c.CustomOperationIds(selector => $"{selector.HttpMethod.ToLower().Pascalize()}{selector.ActionDescriptor.RouteValues["controller"]}");
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My.Portal.Server", Version = "v1" });
});
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.SetIsOriginAllowed(origin => new Uri(origin).IsLoopback)
.WithOrigins(Configuration.GetSection("AllowedOrigins").Get<string[]>())
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My.Portal.Server v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
If i create a new instance in the constructor, then it is working.
thank you in advance!
Example, as per request in comment:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IInfoStorageService>(c => new InfoStorageService(Configuration["ImageInfoConnectionString"]));
This is telling the application to pass an instance of InfoStorageService in where IInfoStorageService is injected. It is instantiated with a connection string that it reads from configuration.
AddScoped means that the injected service will be the same across the request. You can also use AddTransient() which means it will not match any other uses of the service, or you can use AddSingleton(), which means it will use the same instance through the whole lifetime of the application.
Related
I am trying to put Startup class back to .NET 6 project Web API.
So I just altered Program.cs to:
public static class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
and I extracted all service registrations and stuff into my Startup class:
public class Startup
{
public WebApplication InitializeApp()
{
var builder = WebApplication.CreateBuilder();
IServiceCollection servicesservices = builder.Services;
ConfigureServices(servicesservices, builder);
var app = builder.Build();
Configure(app);
return app;
}
public void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder)
{
ConfigurationManager configuration = builder.Configuration;
services.AddApplicationLayer();
services.AddPersistanceLayer(builder.Configuration);
services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VehicleReservation", Version = "v1" });
});
}
public void Configure(WebApplication app)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseErrorHandlingMiddleware();
app.UseAuthorization();
app.MapControllers();
SeedDatabase(app);
}
private void SeedDatabase(WebApplication app)
{
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var vehicleReservationContext = services.GetRequiredService<VehicleReservationContext>();
VehicleReservationContextSeed.SeedAsync(vehicleReservationContext);
}
}
}
but I have an error: `The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection.'
I see that I have 2 params for my ConfigureServices, but Im not sure, how to make it to have 1 or non parameters?
APPROACH #1:
Is to have _builder globally defined within Startup class
public class Startup
{
private WebApplicationBuilder _builder;
public Startup(WebApplicationBuilder builder)
{
_builder = builder;
}
public WebApplication InitializeApp()
{
var _builder = WebApplication.CreateBuilder();
IServiceCollection servicesservices = _builder.Services;
ConfigureServices(servicesservices);
var app = _builder.Build();
Configure(app);
return app;
}
public void ConfigureServices(IServiceCollection services)
{
ConfigurationManager configuration = _builder.Configuration;
services.AddApplicationLayer();
services.AddPersistanceLayer(_builder.Configuration);
services.AddControllers();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VehicleReservation", Version = "v1" });
});
}
public void Configure(WebApplication app)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseErrorHandlingMiddleware();
app.UseAuthorization();
app.MapControllers();
SeedDatabase(app);
}
private void SeedDatabase(WebApplication app)
{
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var vehicleReservationContext = services.GetRequiredService<VehicleReservationContext>();
VehicleReservationContextSeed.SeedAsync(vehicleReservationContext);
}
}
}
Startup classes support configuration injection via ctor, so since you are you only using Configuration from WebApplicationBuilder just inject it:
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// ...
// to clarify configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// ...
}
And then you can use Configuration property in ConfigureServices.
See the docs on the Startup class.
I have the Base URL within the appsettings.json like below
"RM": {
"BaseAddress": "https://rm-dev.abc.org/"
},
With in the Class where I am trying to make a call this endpoint
public class InventorySearchLogic
{
private readonly SMContext _context;
private readonly IConfiguration _iconfiguration;
public InventorySearchLogic(SMContext context, IConfiguration iconfiguration)
{
_context = context;
_iconfiguration = iconfiguration;
}
public InventorySearchLogic(SMContext context)
{
}
public async Task<string> GetRoomID(string roomName)
{
//string rmID = "";
using (var client = new HttpClient())
{
RmRoom retRoom = new RmRoom();
client.BaseAddress = new Uri(_iconfiguration.GetSection("RM").GetSection("BaseAddress").Value);
client.DefaultRequestHeaders.Accept.Clear();
When debugging it throws error like System.NullReferenceException: Message=Object reference not set to an instance of an object. how to access the base URL from appsettings.json
I am not sure how to use the ConfigurationBuilder() as I have different apSettings.json file one for each environment like appsettings.Development.json , appsettings.QA.json, appsettings.PROD.json
Below is my Startup
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.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.AddControllersWithViews();
services.AddSession();
services.AddMemoryCache();
services.AddDbContextPool<SurplusMouseContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("SMConnectionStrings"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
});
});
services.AddHttpContextAccessor();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages()
.AddMicrosoftIdentityUI();
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Customers}/{action=Index}/{id?}");
});
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
You're already injecting an IConfiguration in your service and saving it as _iconfiguration. Assuming that's not the null value, then simply use .GetValue to retrieve a value.
string baseAddress = _iconfiguration.GetSection("RM").GetValue<string>("BaseAddress");
Read more about ASP.Net configuration
Well, it seems that _iconfiguration is also null.
You've indicated in the comments that you're creating an instance of InventorySearchLogic from a controller, such as
// inside controller logic
var searchLogic = new InventorySearchLogic(_context, _iconfiguration);
This is the wrong approach. Instead, you should register this class as a DI service (although you should also add an interface, it's not necessary right now).
In your Startup's ConfigureServices method, add
services.AddTransient<InventorySearchLogic>();
Then instead of manually creating a variable of type InventorySearchLogic, request it though DI
// your controller constructor
private readonly InventorySearchLogic searchLogic;
public MyController(InventorySearchLogic searchLogic)
{
this.searchLogic = searchLogic;
}
This way, InventorySearchLogic's constructor correctly gets the DI services it's looking for. You will have to move the SMContext context. Maybe move that to the method's parameters?
English is not my primary language so I apologize if I make some spelling mistakes here.
I am trying do build a simple asp.net 5.0 application from zero.
Now i'm struggling with de registering process of my appdbcontext class. I'm using a factory that is implementating IDesignTimeDbContextFactory like that:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true)
.AddEnvironmentVariables()
.Build();
var builder = new DbContextOptionsBuilder<AppDbContext>();
//var connectionString = configuration
// .GetConnectionString("DefaultConnection");
var connectionString = "server=127.0.0.1; port=3306; database=dbRoomManagement; uid=root; pwd=room123-pw";
//builder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString),
// x => x.MigrationsAssembly(typeof(ApplicationDbContextFactory).Assembly.FullName));
builder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
return new AppDbContext(builder.Options);
}
}
When i don't register anything on startp.cs like that:
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.AddServices();
services.AddRepositories();
services.AddMappers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "RoomManagement", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RoomManagement v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
I get a error saying that was not possible to resolve my AppDbContext:
If i put the line services.AddDbContext(); to register the AppDbContext i get the message that was mot possible to find the database configurations. I imagine if i use this line the program dont use the factory so they dont find the configurations:
I'm really cant find something that put me in the right direction here.
Does somebody have something that can help me?
Repository: https://github.com/AndreLuis117/RoomManagement
We have a template for our projects in our company in which they write AddTransient<>() methods inside another class. I want to know how to put ConfigureServices method of startup inside another class.
See we have a very simple startup project like this:
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.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
services.AddAutoMapper(typeof(Startup));
}
// 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();
});
}
}
I want to move my (dependent class registration) to another class inside my project.
So this will be my new Startup.cs:
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.AddAutoMapper(typeof(Startup));
}
// 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();
});
}
}
And this will be my ExampleFileName.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
}
First, you have to create a folder named Extensions and there you will create a file name whatever you want. I give my file name is ApplicationService.
Extensions/ApplicationServiceExtensions.cs
namespace API.Extensions
{
public static class ApplicationServiceExtensions
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration config)
{
services.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
return services;
}
}
}
startup.cs
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public IConfiguration Configuration { get; }
//clarify code
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationServices(_config);
//clarify code
}
So,it's an example of putting the ConfigureServices method of startup inside another class. and which you want.
I Typed this blind, but is this what you want?
public abstract class StartUpBase
{
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddTransient<LocationService, LocationService>();
services.AddTransient<PersonService, PersonService>();
services.AddTransient<UserService, UserService>();
}
}
public class StartUp : StartUpBase
{
public override ConfigureServices(IServiceCollection services)
{
services.AddControllers();
base.ConfigureServices(services);
services.AddAutoMapper(typeof(Startup));
}
}
Alternative:
public static class Another
{
public static IServiceCollection AddTransitentServices(IServiceCollection services)
{
//add your transistent services here
return services;
}
}
public class StartUp
{
public override ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services = Another.AddTransitentServices(services)
services.AddAutoMapper(typeof(Startup));
}
}
So, I am trying to set the "Access-Control-Allow-Credentials", using the HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true"); , but it will only work for my GET requests, but not for my POST ones, and i don't know why.
I've also tried to set those in Startup.cs, as so:
services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("My_Web_App")
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And then use it in Configure with app.UseCors("ApiCorsPolicy");
That's the code from my controller, so nothing fancy in here, I think:
[ApiController]
[Route("[controller]")]
[EnableCors("ApiCorsPolicy")]
public class UserController : Controller
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost("RegisterUser")]
public void GetTournaments([FromBody] UserDTO user)
{
HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
_userService.RegisterUser(user);
}
}
My question is, why I can't put the "Access-Control-Allow-Credentials" header using the Headers.add method( Which works for my GET requests ) ? If that is not the correct approach to it, then how to do it ?
Thanks!
Edit:
I've added all my Startup file, as requested:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("http://"MyIpAddressHere"/")
.AllowAnyMethod()
.AllowAnyHeader();
}));
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingGeneral());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddSingleton<ITournamentService, TournamentService>();
services.AddSingleton<IUserService, UserService>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "my_app", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "my_app v1"));
}
app.UseRouting();
app.UseCors("ApiCorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Change
.WithOrigins("My_Web_App")
to
.WithOrigins("http://localhost....") //your web app url
//your Url shouldn't end with "/"
and remove from code:
//sometimes it interfers with token if you have
.AllowCredentials()
// you don't need this at all
HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
Your UseCors should be after UseRouting but before UseAuthorization.
and remove from your controller:
[EnableCors("ApiCorsPolicy")]
I highly suspect that the culprit is in this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
Credentials are not supported without a correct origin.