Getting 'ambiguous call' error/warning in ConfigureServices MVC - asp.net

I am learning ASP.NET and while somewhere I needed this part a few months back ( paused after that) it shows error/warning now. It is a .NET Core app very very basic. I know nothing about the error
See the source code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace WebApplication1
{
public class MyOptions
{
public string color { get; set; }
public string welcomestring { get; set; }
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets();
}
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyOptions>(Configuration);
var foo = Configuration["welcomestring"];
Console.WriteLine(foo);
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Screenshot of error:

give complete name of object with namespace
example
Microsoft.Extensions.DependencyInjection.OptionConfigurationServiceCollectionExtension
or put your cursor at Configure<MyOptions>
and ALT + SHIFT + F10
and select your model.

Related

How to read the Azure App Configuration in Service Fabric ASP.NET Core Stateless Web API?

I need help to read the App Configuration in Service Fabric ASP.NET Core Stateless Web API. In the Normal ASP.NET Core Web API, we can use the Host CreateDefaultBuilder to read the config and use it in the Startup and other classes. If I try to inject in the Service Fabric Web API, it does not work. The Program.cs contains only the following.
private static void Main(string[] args)
{
try
{
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime.RegisterServiceAsync("EmailAPIType",
context => new EmailAPI(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(EmailAPI).Name);
// Prevents this host process from terminating so services keeps running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
And the startup.cs contains
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.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailAPI
{
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();
}
// 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 tried to inject Host CreateDefaultBuilder in program.cs
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(ConnectionString)
.Select(ConfigValues).TrimKeyPrefix(qualtricsAppConfigPrefix + ":")
.UseFeatureFlags();
});
})
.UseStartup<Startup>());
I am running out of Ideas how to do. In Azure Function App we can do it in Startup, not sure how we can handle in Service Fabric ASP.NET Core Web API. Any examples please.
I have uploaded the sample project created in One Drive. Here is the link to it.
https://1drv.ms/u/s!Au2rKbF-hqWY61pykRlWRTI4DB8t?e=vz0c8z
Finally figured it out. For anyone who is interested here is it. If you have any better way to do it please let me know
public class Startup
{
private static string prefix = "";
public Startup(IConfiguration configuration)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", false, false)
.AddEnvironmentVariables();
var builder = configurationBuilder.Build();
configurationBuilder.AddAzureAppConfiguration(o => AddApplicationKeysAppConfiguration(o, builder));
builder = configurationBuilder.Build();
configuration = builder;
Configuration = configuration;
}
private static void AddApplicationKeysAppConfiguration(AzureAppConfigurationOptions options, IConfigurationRoot configuration)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
environment = string.IsNullOrWhiteSpace(environment) ? Environment.GetEnvironmentVariable("Environment") : environment;
string connectionString = "";
options.Connect(connectionString)
.Select($"{prefix}*", environment).TrimKeyPrefix(prefix + ":")
.UseFeatureFlags(flagOptions =>
{
flagOptions.Label = environment;
});
}
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();
}
// 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();
});
}
}
}

DBcontext class in separate class library with Asp.net core webapi application

Solution explorer image and
package manager console image -
I am trying to add migration by giving command like this:
Add-Migration
addingtable -Context SampleApplicationContext" it is throwing
errorUnable to create an object of type 'SampleApplicationContext'.
Add an implementation of
'IDesignTimeDbContextFactory' to the
project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time. mypackagemanagerconsole
My startup project is Sample.Api and default project is datarepository\sampleapplicationdatabase
My SampleApplicationContext is in class library
Please help someone to get of this issue, thanks in advance
my SampleApplicationContext.cs code
-----------------------------------
namespace SampleApplicationDatabase
{
public class SampleApplicationContext:DbContext
{
public SampleApplicationContext(DbContextOptions<SampleApplicationContext> options) : base(options)
{
#if RELEASE
this.Database.Migrate();
#endif
}
public DbSet<AdminCredentials> AdminCredentials { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelBuilder);
}
}
}
my sample.api appsetting code
-----------------------------
{
"SampleApplicationConnectionstring": {
"ConnectionString": "Server=TEKFRIDAY281;Database=SampleApplication;User ID=sa;Password=friday123!;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
my sample.api startup code
--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API_Interface;
using DataAccessLayer;
using IRepository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Repository;
using SampleApplicationDatabase;
namespace Sample.API
{
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.AddTransient<IData, Data>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddControllers();
services.AddMvc();
services.AddDbContext<SampleApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
}
// 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();
});
}
}
}
try to fix you appsettings json
"ConnectionStrings": {
"DefaultConnection": "Data Source=TEKFRIDAY281;Initial Catalog=SampleApplication;User ID=sa;Password=friday123!;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false;"
},
and startup
services.AddDbContext<SampleApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

How can you add a Microsoft Graph client service as a MediatR service in .NET Core 3.1?

So I have a .NET Core web API with it's own local data context, and I'd like to add the ability to call Microsoft Graph as a downstream API.
However, when I try to add the necessary properties to call the Graph API, I get a build error:
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[Application.Users.Me+Query,Microsoft.Graph.User] Lifetime: Transient ImplementationType: Application.Users.Me+Handler': Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'Application.Users.Me+Handler'.)
Here is my startup class:
using API.Middleware;
using Application.TestEntities;
using FluentValidation.AspNetCore;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Persistence;
using Microsoft.Identity.Web;
namespace API
{
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<DataContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
});
});
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
services.AddMediatR(typeof(List.Handler).Assembly);
services.AddControllers(opt =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
opt.Filters.Add(new AuthorizeFilter(policy));
})
.AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
if (env.IsDevelopment())
{
// app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
And my application handler for calling downstream:
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace Application.Users
{
public class Me
{
public class Query : IRequest<User> { }
public class Handler : IRequestHandler<Query, User>
{
private readonly ITokenAcquisition _tokenAcquisition;
private readonly GraphServiceClient _graphServiceClient;
public Handler(ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient)
{
_tokenAcquisition = tokenAcquisition;
_graphServiceClient = graphServiceClient;
}
public async Task<User> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _graphServiceClient.Me.Request().GetAsync();
return user;
}
}
}
}
Hopefully I'm on the right track here, but please let me know if I'm not.
Right so this was a simple oversight on my part.
As per #franklores, you need to register Microsoft Graph in your startup class services:
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
Adding the following to appsettings (scopes may differ):
"DownstreamAPI": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
And be sure to install Microsoft.Identity.Web.MicrosoftGraph to enable the AddMicrosoftGraph() function.

CS0120 An object reference is required for the non-static field, method, or property 'Startup.Configuration'

I'm using .NET Core 3.0.1 and to setup my dbcontext in Services.cs. I've used the below code but this errors is shown:
An object reference is required for the non-static field, method, or
property 'Startup.Configuration'
but tutorials show the same code.
Can anyone see where I could be going wrong?
services.AddDbContext<IPSLContext>(options => options.UseSqlServer(Configuration.GetConnectionString("myDb")));
string connectionString = Configuration.GetConnectionString("myDb");
services.AddDbContext<IPSLContext>(options => options.UseSqlServer(connectionString));
Full .cs file
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SecurityMaintenance.Models;
namespace SecurityMaintenanceCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication()
.AddCookie(options =>
{
options.LoginPath = "/Home/UnauthorizedAccess/";
options.AccessDeniedPath = "/Home/UnauthorizedAccess/";
});
services.AddMvc();
string connectionString = Configuration.GetConnectionString("myDb");
services.AddDbContext<IPSLContext>(options => options.UseSqlServer(connectionString));
}
public static 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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Removed}/{id?}");
});
}
}
}
The thing is that public IConfiguration Configuration { get; } is not static but ConfigureServices which tries to call it is.
Just use public void ConfigureServices(IServiceCollection services) (note the absence of static modifier).

Issue on using AutoMapper in asp.net core

I am following a tutorial on asp.net core and angular. When I add the Automapper inside my Startup class it crashes the dotnet cli and couldn't render the page. This is how I use the Automapper in the Startup:
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 aspcoreangular.persistence;
using AutoMapper;
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.AddAutoMapper();
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");
}
});
}
}
}
This is how I use it in the controller. But it doesn't get to this point
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using aspcoreangular.models;
using aspcoreangular.persistence;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace aspcoreangular.Controllers
{
public class MakesController : Controller
{
private readonly VegaDbContext context;
private readonly IMapper mapper;
protected MakesController(VegaDbContext context, IMapper mapper)
{
this.mapper = mapper;
this.context = context;
}
[HttpGet("/api/makes")]
public async Task<IEnumerable<Resources.MakeResource>> GetMakes()
{
var makes = await context.Makes.Include(m => m.Models).ToListAsync();
return mapper.Map<List<Make>, List<Resources.MakeResource>>(makes);
}
}
}
This is the image of the crash:
Can you please help me with this? Thank you.
This my MakeResouce class
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using aspcoreangular.models;
namespace aspcoreangular.Controllers.Resources
{
public class MakeResource
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ModelResource> Models { get; set; }
public MakeResource()
{
Models = new Collection<ModelResource>();
}
}
}
and in my mappingprofile
using aspcoreangular.Controllers.Resources;
using aspcoreangular.models;
using AutoMapper;
namespace aspcoreangular.ClientApp.Mapping
{
public class MappingProfile : Profile
{
protected MappingProfile()
{
CreateMap<Make, MakeResource>();
CreateMap<Model, ModelResource>();
}
}
}
When AutoMapper maps source object to destination object before mapping itself it has to create an instance of the destination object and then Mapper can map properties using reflection.
And the error says: No parameterless constructor is defined for this object.
That means: AutoMapper kindly asks System.Activator class to create instance of the destination object for him. But System.Activator fails because it can't find public parameterless contructor in destination class (obviously, System.Activator can use constructor with parameters, but AutoMapper hadn't provided any parameters for constructor). And that is why the third line of the Error message comes from Activator.CreateInstance method.
So, to sum up, you should examine Resources.MakeResource class (as destination) for parameterless constructor.
PS. But I can't tell you on Why this exception crashes the whole Application

Resources