我已經開始使用 ASP.NET Core,我一直在使用依賴注入將配置注入到我的 Controller 類中,但它給了我以下錯誤:
InvalidOperationException:嘗試激活“API.Controllers.UsersController”時無法決議“API.SQLConnection.IDBConnection”型別的服務
用戶控制器 (UserController.cs)
public class UsersController : ControllerBase
{
private readonly IDBConnection _isqlConnection;
private readonly DataContext _context; // here we have used dependency injection so that we can access the data from the DataContext class.
public UsersController(DataContext context)
{
_context = context;
}
public UsersController(IDBConnection connection)
{
_isqlConnection = connection;
}
[HttpGet]
public ActionResult<IEnumerable<AppUser>>GetUsers() // we are going to be returning a type of action result.
{
_isqlConnection.GetConnection().Open();
var user = _context.Users.ToList();
_isqlConnection.GetConnection().Close();
return user;
}
啟動 (Startup.cs)
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration configuration)
{
_config = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options =>
{
options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
});
services.AddHttpContextAccessor();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
});
}
應用用戶 (AppUser.cs)
public class AppUser
{
public int Id { get; set; }
public string Username { get; set; }
}
資料背景關系(DataContext.cs)
public class DataContext : DbContext
{
public DbSet<AppUser> Users { get; set; }
public DataContext(DbContextOptions options) : base(options)
{
}
}
DBConnection (DBConnection.cs)
public interface IDBConnection
{
SqlConnection GetConnection();
}
public class DBConnection : IDBConnection
{
public SqlConnection con = new SqlConnection(@"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DatingSite;Integrated Security=True");
public SqlConnection GetConnection()
{
return con;
}
}
不太確定有什么問題有人有任何想法嗎?
uj5u.com熱心網友回復:
我假設您需要向依賴注入容器注冊服務,因為您將它用于依賴注入。在Startup.csin 中ConfigureServices(),嘗試添加:
services.AddScoped<IDBConnection, DBConnection>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331418.html
