【发布时间】: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; }
}
}
由于错误提到了UserController 和ConnectionString 类,我只添加了其中的两个。
让我知道如何解决这个问题。谢谢
【问题讨论】:
-
你能把这行
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