【问题标题】:Error while running .net core web api project运行 .net core web api 项目时出错
【发布时间】:2021-11-29 09:15:30
【问题描述】:

我正在学习 .net core web api。试图连接mysql。出现错误后出现错误

System.InvalidOperationException: Unable to resolve service for type 'WebApplication4.Models.ConnectionStrings' while attempting to activate 'WebApplication4.Controllers.UserController'.
  at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
  at lambda_method9(Closure , IServiceProvider , Object[] )
  at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
  at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
  at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
  at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()

这是我的Startup.cs,看起来像这样

using Microsoft.AspNetCore.Builder;
using Microsoft.OpenApi.Models;
using WebApplication4.Models;

namespace WebApplication4
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; }
        public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env)
        {
            var appsettings = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .Build();
            Configuration = appsettings;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            ConnectionStrings con = new ConnectionStrings();
            Configuration.Bind("ConnectionStrings", con);
            services.AddSingleton(con);

            services.AddControllers();
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = ".Net Core 3 Web API", Version = "v1" });
            var filePath = Path.Combine(AppContext.BaseDirectory, "NetCore3WebAPI.xml");
            c.IncludeXmlComments(filePath);
            });
        }

        // 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.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", ".Net Core 3 Web API V1");
            });
        }
    }
}

Usercontroller.cs

using Dapper;
using Microsoft.AspNetCore.Mvc;
using MySqlConnector;
using WebApplication4.Models;
using System.Threading.Tasks;

namespace WebApplication4.Controllers
{
    [Route("api/User")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Models.ConnectionStrings con;
        public UserController(Models.ConnectionStrings c)
        {
            con = c;
        }

        /// <summary>
        /// List users
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] Models.User vm)
        {
            return await Task.Run(() =>
            {
                using (var c = new MySqlConnection(con.MySQL))
                {
                    var sql = @"SELECT * FROM user 
                                WHERE (@id = 0 OR id = @id) 
                                AND (@name IS NULL OR UPPER(name) = UPPER(@name))";
                    var query = c.Query<Models.User>(sql, vm, commandTimeout: 30);
                    return Ok(query);
                }
            });
        }

        /// <summary>
        /// Create user
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] Models.User vm)
        {
            return await Task.Run(() =>
            {
                using (var c = new MySqlConnection(con.MySQL))
                {
                    var sql = @"INSERT INTO user (name) VALUES (@name)";
                    c.Execute(sql, vm, commandTimeout: 30);
                    return Ok();
                }
            });
        }
    }
}

ConnectionStrings.cs

namespace WebApplication4.Models
{
    public class ConnectionStrings
    {
        public string MySQL { get; set; }
    }
}

由于错误提到了UserControllerConnectionString 类,我只添加了其中的两个。

让我知道如何解决这个问题。谢谢

【问题讨论】:

  • 你能把这行ConnectionStrings con = new ConnectionStrings();改成WebApplication4.Models.ConnectionStrings con = new WebApplication4.Models.ConnectionStrings();吗?
  • @Llama 试过了。还是一样的错误
  • 你确定StartUp.cs中注册的ConnectionString对象和UserController的构造函数中的ConnectionStrings是一样的吗?有时 2 个类名相同,但它们位于不同的命名空间中。
  • @NikhilAgrawal 是的。

标签: c# .net asp.net-mvc


【解决方案1】:

您正在创建一个连接字符串的单例。但话又说回来,不要在任何地方注射它。结果控制器无法找到它正在寻找的东西。

更好的方法是使用配置对象本身。可以在应用程序的任何地方重用。以下是在控制器中构建和注入配置的方法:

启动类:

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration, Microsoft.Extensions.Hosting.IHostingEnvironment env)
{
    Configuration = configuration;
}

控制器:

using Microsoft.Extensions.Configuration;

private IConfiguration _configuration;

public UserController(IConfiguration configuration)
{
    _configuration = configuration;
}

public async Task<IActionResult> Get([FromQuery] Models.User vm)
{
    var connstring= _configuration.GetValue<string>("ConnectionStrings:DefaultConnection");
}

【讨论】:

  • 要不要修改启动类的构造函数???
  • 没有。只需在其中添加IConfiguration configuration。我已经更新了我的示例代码。
  • 并且connstring必须是get方法的第一行???
  • 你的意思是配置?
  • var connstring= _configuration.GetValue("ConnectionStrings:DefaultConnection");
猜你喜欢
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多