Unable to resolve service for type 'System.Net.Http.HttpClient'

I created a ViewComponent class which call a REST API using the HttpClient, this is the code:

public class ProductsViewComponent : ViewComponent
{
    private readonly HttpClient _client;

    public ProductsViewComponent(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    public async Task<IViewComponentResult> InvokeAsync(string date)
    {
        using(var response = await _client.GetAsync($"/product/get_products/{date}"))
        {
            response.EnsureSuccessStatusCode();
            var products = await response.Content.ReadAsAsync<List<Products>>();
            return View(products);
        }
    }
}

I get this error:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate MyApp.ViewComponents.ProductsViewComponent'

I injected the HttpClient in the ConfigureService method available in Startup in this way:

 services.AddHttpClient<FixturesViewComponent>(options =>
 {
    options.BaseAddress = new Uri("http://80.350.485.118/api/v2");
 });

UPDATE:

I registered the ProductsViewComponent too, same error.

Score: 18
Tags: c#, asp.net, asp.net-core
Views: 23299
Date posted: 9/5/2018

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`

I writing code for adding roles to users in my asp.net core project

Here is my Roles controller.

public class RolesController : Controller
{
    RoleManager<IdentityRole> _roleManager;
    UserManager<AspNetUsers> _userManager;
    public RolesController(RoleManager<IdentityRole> roleManager, UserManager<AspNetUsers> userManager)
    {
        _roleManager = roleManager;
        _userManager = userManager;
    }
    public IActionResult Index() => View(_roleManager.Roles.ToList());

    public IActionResult Create() => View();
    [HttpPost]
    public async Task<IActionResult> Create(string name)
    {
        if (!string.IsNullOrEmpty(name))
        {
            IdentityResult result = await _roleManager.CreateAsync(new IdentityRole(name));
            if (result.Succeeded)
            {
                return RedirectToAction("Index");
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
        }
        return View(name);
    }

    [HttpPost]
    public async Task<IActionResult> Delete(string id)
    {
        IdentityRole role = await _roleManager.FindByIdAsync(id);
        if (role != null)
        {
            IdentityResult result = await _roleManager.DeleteAsync(role);
        }
        return RedirectToAction("Index");
    }

    public IActionResult UserList() => View(_userManager.Users.ToList());

    public async Task<IActionResult> Edit(string userId)
    {
        // получаем пользователя
        AspNetUsers user = await _userManager.FindByIdAsync(userId);
        if(user!=null)
        {
            // получем список ролей пользователя
            var userRoles = await _userManager.GetRolesAsync(user);
            var allRoles = _roleManager.Roles.ToList();
            ChangeRoleViewModel model = new ChangeRoleViewModel
            {
                UserId = user.Id,
                UserEmail = user.Email,
                UserRoles = userRoles,
                AllRoles = allRoles
            };
            return View(model);
        }

        return NotFound();
    }
    [HttpPost]
    public async Task<IActionResult> Edit(string userId, List<string> roles)
    {

        AspNetUsers user = await _userManager.FindByIdAsync(userId);
        if(user!=null)
        {

            var userRoles = await _userManager.GetRolesAsync(user);

            var allRoles = _roleManager.Roles.ToList();

            var addedRoles = roles.Except(userRoles);

            var removedRoles = userRoles.Except(roles);

            await _userManager.AddToRolesAsync(user, addedRoles);

            await _userManager.RemoveFromRolesAsync(user, removedRoles);

            return RedirectToAction("UserList");
        }

        return NotFound();
    }
}

But when I run app and going to Roles controller. I get this error

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'VchasnoCrm.Controllers.RolesController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

How I can fix this?

Score: 12
Tags: c#, asp.net, .net, asp.net-identity
Views: 9761
Date posted: 12/16/2018

Unable to resolve service for type 'Microsoft.AspNetCore.Cors.Infrastructure.ICorsService

I observe an exception executing the following code:

[<EntryPoint>]
let main argv =                         
    WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .Configure(Action<IApplicationBuilder> configureApp)
        .ConfigureServices(Action<IServiceCollection> configureServices)
        .Build()

Error:

Unable to resolve service for type 'Microsoft.AspNetCore.Cors.Infrastructure.ICorsService

Details:

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Cors.Infrastructure.ICorsService' while attempting to activate 'Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware'.'

I added the Cors code here:

let configureServices (services : IServiceCollection) =
    ...
    services.AddAuthentication() |> ignore
    services.AddCors |> ignore // Enables CORS

Note:

This all use to work until I added ASP.Net WebAPI support for some json that I was struggling with.

In addition, I also upgraded my Nuget packages to 2.0.

The source code can be found on GitHub.

Score: 11
Tags: asp.net-core, f#
Views: 5711
Date posted: 10/22/2017

System.InvalidOperationException: Unable to resolve service for type

I'm working on a Web API with ASP.NET Core. When I'm executing my API with a post request, an exception is throwing before my break point in the Post method of UnitController.

Exception

Request starting HTTP/1.1 POST http://localhost:5000/api/unit application/json 31 fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HKVTL9A1LTD4": An unhandled exception was thrown by the application. System.InvalidOperationException: Unable to resolve service for type 'Project.DataAccess.Repository.UnitRepository' while attempting to activate 'Project.Service.UnitService'.

Context

namespace Project.DataAccess.Library.Interface {
public interface IBaseRepository<M> where M : class, IEntity
{
    IEnumerable<M> SelectAll();

    M SelectByID(int id);

    void Insert(M obj);

    void Update(M obj);

    void Delete(int id);

    void Save();
}
}

namespace Project.DataAccess.Library {
public abstract class BaseRepository<M> : IBaseRepository<M> where M : class, IEntity
{
    protected ProjectContext Db { get; }
    private DbSet<M> table = null;

    protected DbSet<M> Table
    {
        get
        {
            return this.table;
        }
    }

    public BaseRepository(ProjectContext dbContext)
    {
        Db = dbContext;
        this.table = Db.Set<M>();
    }

    public void Delete(int id)
    {
        M existing = this.SelectByID(id);
        if (existing != null)
            this.table.Remove(existing);
    }

    // others methods
}
}

namespace Project.DataAccess.Repository
{
    public class UnitRepository : BaseRepository<Unit>, IUnitRepository
    {
        public UnitRepository(Projectcontext) : base(context) { }
    }
}

namespace Project.Service
{
    public class UnitService : BaseService<Unit>, IUnitService
    {
        public UnitService(UnitRepository unitRepository) : base(unitRepository) { }
    }
}


namespace AssoManager.Service.Library
{
    public abstract class BaseService<M> : IBaseService<M> where M : class, IEntity
    {
        private IBaseRepository<M> _repository;

        public BaseService(IBaseRepository<M> repository)
        {
            _repository = repository;
        }

        public IEnumerable<M> GetAll()
        {
            return this._repository.SelectAll();
        }
    }
 }


namespace Project
{
    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();
            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)
        {
            // Add framework services.
            services.AddMvc();

            this.DataAccessMySqlConfiguration(services);
            this.ConfigureRepository(services);
            this.ConfigureServicesUnit(services);
            this.ConfigureServicesUser(services);
        }

        // 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.UseMvc();
        }

        #region Database configuration

        public void DataAccessMySqlConfiguration(IServiceCollection services)
        {
            services.AddDbContext<ProjectContext>(options => options.UseMySQL(Configuration.GetConnectionString("MsSQLConnection")));
        }

        #endregion

        #region DataAccess configuration

        public void ConfigureRepository(IServiceCollection services)
        {
            services.AddScoped<IUnitRepository, UnitRepository>();
            services.AddScoped<IUserRepository, UserRepository>();
        }

        #endregion

        #region Services configuration

        /// <summary>
        /// Is used to add unit services to the container
        /// </summary>
        public void ConfigureServicesUnit(IServiceCollection services)
        {
            services.AddTransient<IUnitService, UnitService>();
            services.AddTransient<IMeetingService, MeetingService>();
        }

        /// <summary>
        /// Is used to add user services to the container
        /// </summary>
        public void ConfigureServicesUser(IServiceCollection services)
        {
            services.AddTransient<IUserService, UserService>();
        }

        #endregion Services configuration
    }
}


namespace Project.Controllers
{
    [Route("api/[controller]")]
    public class UnitController : Controller
    {
        private IUnitService UnitService;

        public UnitController(IUnitService unitService)
        {
            UnitService = unitService;
        }

        // GET api/units
        [HttpGet]
        public IEnumerable<Unit> Get()
        {
            return UnitService.GetAll();
        }

        // GET api/unit/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            Unit unit;
            //->Check
            if (id < 1)
                return BadRequest();
            //->Processing
            unit = UnitService.GetByID(id);
            if (unit == null)
                return NotFound();
            return new ObjectResult(unit);
        }

        // POST api/unit
        [HttpPost]
        public IActionResult Post([FromBody]Unit unit)
        {
            //->Check
            if (unit == null)
                return BadRequest();
            //->Processing
            UnitService.Create(unit);
            return CreatedAtRoute("Get", new { id = unit.Id }, unit);
        }

        // PUT api/unit/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/unit/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Version

"dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.0",
    "MySql.Data.Core": "7.0.4-IR-191",
    "MySql.Data.EntityFrameworkCore": "7.0.4-IR-191",
    "IdentityServer4": "1.0.0-rc2",
    "AssoManager.Domain": "1.0.0-*",
    "AssoManager.Service": "1.0.0-*",
    "AssoManager.DataAccess": "1.0.0-*"
  },

Question

I think the problem is maybe with the inheritance between BaseRepository and IBaseRepository. But I don't understand where could be my mistake. How can I correct this bug ?

Thank you for your helps :),

Score: 7
Tags: c#, dependency-injection, asp.net-core, .net-core, asp.net-core-webapi
Views: 9439
Date posted: 10/26/2016

Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'

In my MVC application, I get an event from the RabbitMQ queue. To start processing the event

public void Consume()
{
    ConnectionFactory factory = new ConnectionFactory
    {
        //..
    };

    IConnection connection = factory.CreateConnection();
    IModel channel = connection.CreateModel();
    channel.QueueDeclare("MyQueueName", true, false, false, null);

    EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
    consumer.Received += OnReceived;
    channel.BasicConsume("MyQueueName", true, consumer);
}

To process the event I use

private async void OnReceived(object model, BasicDeliverEventArgs deliverEventArgs)
{
    var info = Encoding.UTF8.GetString(deliverEventArgs.Body);            
    var model = JsonConvert.DeserializeObject<MyModel>(info);
    if (model != null)
    {
        await _groupServiceProvider.GetService<IMyService>().ProcessEvent(model);
    }
}

Finally, to process/update my model I use

public class MyService : IMyService
{
    private readonly IHostingEnvironment _env;

    public MyService(IHostingEnvironment env)
    {
        _env = env;
    }        

    public async Task ProcessEvent(MyModel model)
    {
        //.. process model
    }        
}

Unfortunatelly when I run my app I get

Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'MyProject.MyService'.

at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet1 callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider) at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd[TKey,TValue,TArg](ConcurrentDictionary2 dictionary, TKey key, Func3 valueFactory, TArg arg) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at MyService.Consumerd__3.MoveNext() in ..\MyService\Consumers.cs:line

Can anyone explain how can I resolve the dependencies, please?

Edit

To inject dependency I use Microsoft.Extensions.DependencyInjection.ServiceCollection

_groupServiceProvider = new ServiceCollection()                
             .AddAutoMapper(typeof(AutoMapperProfile)) 
             .AddSingleton<IMyService, MyService>()                
             .AddSingleton<IHostingEnvironment, HostingEnvironment>()
             //..
            .BuildServiceProvider();
Score: 5
Tags: c#, rabbitmq
Views: 5865
Date posted: 9/7/2017


1


© 2021 Search Overflow
Contributions licensed under cc by-sa