using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Travel.Application;
using Travel.WebApi.Filters;
using Travel.Data;
using Travel.Shared;
namespace Travel.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication();
services.AddInfrastructureData();
services.AddInfrastructureShared(Configuration);
services.AddHttpContextAccessor();
services.AddControllers();
services.AddControllersWithViews(options =>
options.Filters.Add(new ApiExceptionFilter()));
services.Configure<ApiBehaviorOptions>(options =>
options.SuppressModelStateInvalidFilter = true
);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Travel.WebApi", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Travel.WebApi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
So this is my "StartUp" file and I have an error that says :
Severity Code Description Project File Line Suppression State
Error CS1061 'IServiceCollection' does not contain a definition for
'AddInfrastructureData' and no accessible extension method
'AddInfrastructureData' accepting a first argument of type
'IServiceCollection' could be found (are you missing a using directive
or an assembly
reference?) Travel.WebApi C:\Users\Alexandru\Desktop\WebDev\AdminApp\src\presentation\Travel.WebApi\Startup.cs 26 Active
I just.. am stuck. Why can it not find "AddInfrastructureData"?
Try to add a using namespace where the AddInfrastructureData resides.
Replace Travel.Data with the appropriate namespace from your code:
namespace Travel.Data;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddInfrastructureData(this IServiceCollection servicesCollection)
{
//...
return servicesCollection;
}
}
// Startup.cs
using Travel.Data;
If the extension method is located in a different project or package add it via right clicking the Dependencies submenu of the project and select "Add Project Reference..." or "Manage NuGet Packages...".
Please provide more info in case that it was not helpful. Is the AddInfrastructureData your own method or an external one etc?
you could check your guide book if you have missed any packages
and you could check your guide book if you have missed to copy the codes like below:
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructureData(this IServiceCollection services)
{
return services;
}
public static IServiceCollection AddInfrastructureShared(this IServiceCollection services,IConfiguration configuration)
{
return services;
}
}
Related
I'm new to ASP .NET Core, however I've had coded ASP .NET before, now I am following this tutorial
"https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio-code".
I am using Visual Studio Code.
I'm doing the "Scaffold a controller" section.
When I run the last dotnet statement, stated in that section, I get the error that I refer on the title (same error that shows on my problems tab inside the terminal).
Problem is, that the error can be resolved by inserting a "using" statement, as it's shown on the section "Register the database context".
I have followed thoroughly all the steps, but when it comes to using TodoApi.Models, I get the error
Type or namespace name 'Models' does not exist in namespace 'TodoApi' (assembly reference missing?) [TodoApi]
I have read many threads but none seem to answer the question regarding my specific case, here I'll show some of my code so you can compare mine with the Tutorial's
My Startup.cs file:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
namespace TodoApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I'm meant to call this method at startup but it's not reference anywhere:
dbContext.Database.Migrate();
Type DatabaseFacade does not contain a definition for Migrate and no
extension method Migrate of type DatabaseFacade could be found (are you missing
a using directive or an assembly reference?
So which using / assembly am I missing?
I needed to add the following dependencies via NuGet.
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Just import EntityFrameworkCore by typing the following at the top:
using Microsoft.EntityFrameworkCore;
var migrator = dbContext.Database.GetService<IMigrator>();
await migrator.MigrateAsync("targetMigration", cancellationToken);
(For.Net Core) After adding the package (Oracle/SQLServer)
enter image description here
you can design the startup.cs like this using extensions.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
.UseSwaggerUI()
.UseRouting()
.UseCors(options => options
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod())
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
})
.ApplyMigrations();
}
So you can call ApplyMigrations as below.
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace SocialRebate.WebApi.Infrastructure.Extensions
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseSwaggerUI(this IApplicationBuilder app)
=> app
.UseSwagger()
.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API");
options.RoutePrefix = string.Empty;
});
public static void ApplyMigrations(this IApplicationBuilder app)
{
using var services = app.ApplicationServices.CreateScope();
var dbContext = services.ServiceProvider.GetService<YourDbContext>();
dbContext.Database.Migrate();
}
}
}
In the constructor of your DataContext class you can use
this.Database.Migrate();
and it should do just fine.
I'm totally new to ASP.NET. I wanted to create small API. I tried to connect that API with Microsoft Sql Server. But it gives an error which is
InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc' inside the call to 'ConfigureServices(...)' in the application startup code
My Startup.cs file is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
//using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;
using myApp.Models;
namespace myApp
{
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)
{
var connection = #"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
That error is indicate in app.UseMvc(); . Can you anyone help me to solve this problem?
after the services.AddDbContext …
just add services.AddMvc()
(just as the error Msg suggested )
public void ConfigureServices(IServiceCollection services)
{
var connection = #"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
services.AddMvc()
}
I get an error when I build my project 'The type or namespace name 'VegaDbContext' could not be found (are you missing a using directive or an assembly reference?)'. I am following a tutorial using vs code editor. This is what I have in my "Startup" class:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using VegaDbContext;
namespace aspcoreangular
{
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.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
and this is my dbcontext:
using Microsoft.EntityFrameworkCore;
namespace aspcoreangular.persistence
{
public class VegaDbContext : DbContext
{
public VegaDbContext(DbContextOptions<VegaDbContext> options) : base(options)
{ }
}
}
One thing I have noticed as well, in vs code, I do not get red lines if there is an error in my code. That's the reason maybe that I do not see the errors in it. Can you please help me with this.
Replace
using VegaDbContext;
with
using aspcoreangular.persistence;
You are referencing the VegaDbContext context in your Using Directive , and not the namespace it belongs to
Further reading
using Directive (C# Reference)
I'm trying to use Quartz sheduker in my asp core 2.0 project.
I downloaded Quartz 3.0.4 using nuget and after that i added services.AddQuartz(new QuartezOptions {});
to ConfigureService function in Startup.cs
I also have the same problem with app.UseQuartz()
Thats, how Startup.cs is looking now:
using AspProj.Map;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Quartz;
namespace AspProj
{
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.AddDbContext<CacheDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DB")));
services.AddScoped<CacheDbContext>();
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
});
services.AddQuartz(new QuartezOptions { });
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "DbApi V1");
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseQuartz();
}
}
}
I tried to connect different Quartz namespaces through using, but it has no use.
I just keep getting "IServiceCollection does not contain definition for AddQuartz" from visual studio 2017.
error screenshot
I cant find any information about someone with the same problem as me.
Did sombody knows, how can i fix this?
Try to add the Quartz namespace in your dependencies and this should work:
using Quartz;
Also ensure that the proper package has been installed:
dotnet add package Quartz.Extensions.Hosting
need to install package Quartz.NET Microsoft.Extensions.DependencyInjection