ServiceCollection does not contain a definition from "AddLogging" - c#

I'm currently trying to create a Logger so I can inject it in Unit Tests. I'm following https://stackoverflow.com/a/43425633/1057052, and it used to work! I then moved the project and reestablished the dependencies, and now I'm getting
'ServiceCollection' does not contain a definition for 'AddLogging' and
no accessible extension method 'AddLogging' accepting a first argument
of type 'ServiceCollection' could be found (are you missing a using
directive or an assembly reference?)
There must be something silly I'm missing. Currently under ASP.NET Core 2.2, and I believe I have assigned the correct dependencies.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection?view=aspnetcore-2.2
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.loggingservicecollectionextensions.addlogging?view=aspnetcore-2.2
I've been reinstalling for the past hour our so! Can't nail what the problem is
Here's the code:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Planificacion.UnitTest.Config
{
public class LoggerTestConfig
{
private LoggerTestConfig()
{
}
// https://stackoverflow.com/a/43425633/1057052
public static ILogger<T> GetLoggerConfig<T>() where T : class
{
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var factory = serviceProvider.GetService<ILoggerFactory>();
return factory.CreateLogger<T>();
}
}
}

The image highlights that the dependency injection dll is referenced, but desired LoggingServiceCollectionExtensions.AddLogging Method as shown in the links provided, indicates
Namespace: Microsoft.Extensions.DependencyInjection
Assembly: Microsoft.Extensions.Logging.dll <----NOTE THIS
Which is not referenced as shown in the image.
Add a reference to the Microsoft.Extensions.Logging.dll assembly stated above.

Related

'IServiceCollection' does not contain a definition for 'AddIdentity'

Before I tested this line on a web application in core 5.
services.AddIdentity<Operator, IdentityRole>().AddEntityFrameworkStores<StorageContext>().AddDefaultTokenProviders();
This works fine in startup class.
Now I want to know how to implement it in windows form, Core 7. Because I just get this error -
'IServiceCollection' does not contain a definition for 'AddIdentity'
and no accessible extension method 'AddIdentity' accepting a first
argument of type 'IServiceCollection' could be found (are you missing
a using directive or an assembly reference?)
Am I missing assemblies? what are they?
this is my code now -
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddScoped<IStorageRepository, StorageRepository>();
services.AddDbContext<StorageContext>(option =>
{
option.EnableSensitiveDataLogging(true);
option.UseSqlServer(configuration["Data:Storage:ConnectionString"]);
});
services.AddIdentity<Operator, IdentityRole>().AddEntityFrameworkStores<StorageContext>().AddDefaultTokenProviders();
});
}
Does this AddIdentity class works in Winforms?
Just try to install Microsoft.AspNetCore.Identity package.
I had the same problem, just try to add this nugget package Microsoft.AspNetCore.Identity.UI. I add it and it start see it

'IServiceCollection' does not contain a definition for 'AddControllers' even added newtonjson

I have a ASP.NET Core 5.0.1 project and planning to create authentication on swagger UI but I encounter some issues on the services controller. Which is the error code below. Regarding this I have seen an issue similar to me in this Link but my issue is not resolve even added the NewtonsoftJson. Any ideas on this kind of issue.
Error CS1061 'IServiceCollection' does not contain a definition for
'AddControllers' and no accessible extension method 'AddControllers'
accepting a first argument of type 'IServiceCollection' could be found
(are you missing a using directive or an assembly reference?
using Microsoft.Owin;
using Owin;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
[assembly: OwinStartup(typeof(ABSRestService.App_Start.Startup1))]
namespace ABSRestService.App_Start
{
public class Startup1
{
public Startup1(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigurationServices(IServiceCollection services)
{
services.AddControllers();
}
}
}
At first Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJsonand then
Try this, it should work.
services.AddControllers().AddNewtonsoftJson();

'IServiceCollection' does not contain a definition for 'AddAWSService' and no accessible extension method 'AddAWSService' error in asp.net core 2.2?

I am setting up Aws SQS in asp.net core 2.22 project. I am adding aws configuration lines in my Program.cs file. Here is my Program.cs file.
using Amazon.SQS;
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;
namespace analytics
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; set;}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options =>
{
options.AllowAnyOrigin();
});
});
// AWS Configuration
var awsoptions = Configuration.GetAWSOptions();
services.AddDefaultAWSOptions(awsoptions);
services.AddAWSService<IAmazonSQS>();
// Worker Service
// services.AddHostedService<Worker>();
}
// 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
{
// 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.UseMvc();
app.UseCors(options =>
{
options.AllowAnyOrigin();
});
}
}
}
So i am receiving these errors on console
Startup.cs(40,52): error CS1061: 'IConfiguration' does not contain a definition for 'GetAWSOptions'
and no accessible extension method 'GetAWSOptions' accepting a first argument of type
'IConfiguration' could be found (are you missing a using directive or an assembly reference?)
[D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Startup.cs(41,30): error CS1061: 'IServiceCollection' does not contain a definition for
'AddDefaultAWSOptions' and no accessible extension method 'AddDefaultAWSOptions' accepting a first
argument of type 'IServiceCollection' could be found (are you missing a using directive or an
assembly reference?) [D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Startup.cs(42,30): error CS1061: 'IServiceCollection' does not contain a definition for
'AddAWSService' and no accessible extension method 'AddAWSService' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using directive or an assembly
reference?) [D:\OfficeProjects\beelinksanalytics\analytics.csproj]
Basically i want to implement Aws SQS service to listen queue messages and want to perform some actions based on those messages. So i am struggling to configure Aws Sdk and aws sqs in asp.net core 2.2 project
I didn't find any relevant documentation of how to configure aws sqs in asp.net core 2.2. Please tell me what's wrong with this?
just run this in your command line as mentioned #panagiotis-kanavos (select version that you want here)
dotnet add package AWSSDK.Extensions.NETCore.Setup --version 3.3.101
verify that the reference was added in your .csproj
this worked for me, I hope as well for you

The type or namespace name does not exist

I know there are several similar topics like this on this site, but I can't find a solution that works. I have a solution called 'SportsStore' and it contains 3 projects, ALL that use the full .NET 4 framework. The projects are named 'SportsStore.Domain', 'SportsStore.UnitTests' and 'SportsStore.WebUI'.
Within the 'SportsStore.WebUI' project, I created a folder called 'Infrastructure' and in it I have a class called 'NinjectControllerFactory.cs' The complete code for it is below. Note the last 'using' statement at the top: 'using SportsStore.Domain.Abstract'. My program will NOT compile and it tells me the namespace does not exist. Intellisense recognizes 'SportsStore' but only says 'WebUI' is my next option. It will not recognize 'SportStore.Domain' at all. I have tried cleaning, rebuilding, closing, opening, rebooting, changing frameworks back to Client for all projects and then back to Full, and nothing seems to work.
Bottom line is I'm trying to get access to my IProductRepository.cs repository file which is part of the SportsStore.Domain.Abstract namespace in the 'SportsStore.Domain' project.
I'm hoping this is something easy to correct? Thanks in advance!
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using System.Linq;
using Ninject;
using Moq;
using SportsStore.Domain.Abstract;
//To begin a project that uses Ninject and/or Moq (mocking data) you
//need to add reference to them. Easiest way is to select 'View', then
//'Other Windows', and 'Package Manager Console'. Enter the commands:
//Install-Package Ninject -Project SportsStore.WebUI
//Install-Package Ninject -Project SportsStore.UnitTests
//Install-Package Moq -Project SportsStore.UnitTests
//We placed this file in a new folder called 'Infrastructure' within the
//'SportsStore.WebUI' project. This is a standard way to define what we
//need to do with Ninject since we are going to use Ninject to create our
//MVC application controllers and handle the dependency injection (DI).
//To do this, we need to create a new class and make a configuration
//change.
//Finally we need to tell MVC that we want to use this class to create
//controller objects, which we do by adding a statement to the
//'Global.asax.cs' file in this 'SportsStore.WebUI' project.
namespace SportsStore.WebUI.Infrastructure
{
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
//During development, you may not want to hook your IProductRepository to
//live data yet, so here we can create a mock implementation of the data
//and bind it to the repository. This is MOQ in work - great tool to allow
//you to develop real code and make it think it's using the live data. This
//uses the 'System.Linq' namespace
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>
{
new Product { Name = "Football", Price = 25 },
new Product { Name = "Surf board", Price = 179 },
new Product { Name = "Running shoes", Price = 95 }
}.AsQueryable());
ninjectKernel.Bind<IProductRepository>().ToConstant(mock.Object);
}
}
}
In order for a class to access a type declared in another assembly, you must reference them. If you are using Ninject (I suppose), you have did this to the Ninject assembly.
Even though Domain is an assembly of yours, on the same solution, you must reference it at the WebUI, otherwise they won't know each other.
So, let's make sure:
Right click your WebUI project
Select Add reference
Go to Project tab
Select Domain project
Done!
Rebuild and you're good to go!
Regards

Missing extension methods in HtmlHelper using NHaml

I discovered NHaml some days ago and it's a great project.
When I try to use MVC2 Html helpers like Html.LabelFor(), Html.TextBoxFor(); the views won't compile.
Example:
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'LabelFor' and no extension method 'LabelFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0185: textWriter.Write(" ");
0185: textWriter.Write(Convert.ToString(Html.LabelFor(model => model.Username)));
0187: textWriter.WriteLine();
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0194: textWriter.Write(" ");
0194: textWriter.Write(Convert.ToString(Html.TextBoxFor(model => model.Username)));
0196: textWriter.WriteLine();
I tried to add assemblies and namespaces in the nhaml's Web.config section but it doesn't change anything.
I'm using :
System.Web.Mvc 2.0
.NET Framework 3.5 SP1
Nhaml 1.5.0.2 from git trunk (and tried other builds)
My NHaml configuration is:
<nhaml autoRecompile="true" templateCompiler="CSharp3" encodeHtml="false" useTabs="false" indentSize="2">
It looks like you have an assembly reference problem.
You are probably referencing the MVC 1.0 assemblies, instead of 2.0 assemblies?
The problem is the view class contains a non-generic HtmlHelper. Or some new extension methods requires the ViewData.Model's type.
To correct this problem, change the property and instantiation in NHaml.Web.Mvc/NHamlMvcView.cs.
//public HtmlHelper Html { get; protected set; } // line 42
public HtmlHelper<TModel> Html { get; protected set; }
//Html = new HtmlHelper( viewContext, this ); // line 37
Html = new HtmlHelper<TModel>( viewContext, this );
Rebuild and use :)
As far as I can see the new MVC helpers are not supported, actually only a limited amount of HtmlHelpers are namely LinkExtensions. As a wild guess, you can possibly try to adding the LabelExtensions to the setup of the NHaml viewengine in the NHaml.Web.Mvc/NHamlMvcViewEngine.cs file (since you do have the source) and check if that works.
private void InitializeTemplateEngine()
{
// snip
_templateEngine.Options.AddReference( typeof( LabelExtensions ).Assembly.Location ); // Line 50
}

Categories