我正在编写我的第一个ASP.NET Core Web API,并试图弄清楚如何将我的DbContext对象注入到我的repository构造函数中。我按照这个教程中的EF部分进行操作,其中DbContext通过
我能够将DbContext注入控制器并调用存储库方法将其分配给UserRepository。请注意保留HTML标记。
services.AddDbContext<DbContext>
被注册到服务集合中,services.GetRequiredService<DbContext>()
用于初始化数据库值。 public class Startup
{
public IConfiguration Configuration {
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IItemRepository, ItemRepository>();
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
services.AddDbContext<RAFYCContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
}
public class Program
{
public static void Main(string[] args)
{
//CreateWebHostBuilder(args).Build().Run();
IWebHost host = CreateWebHostBuilder(args).Build();
using (IServiceScope scope = host.Services.CreateScope())
{
IServiceProvider services = scope.ServiceProvider;
try
{
RAFYCContext context = services.GetRequiredService<RAFYCContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
ILogger logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
}
我能够将DbContext注入控制器并调用存储库方法将其分配给UserRepository。请注意保留HTML标记。
public class UserController : ControllerBase
{
IUserRepository _userRepo;
public UserController(IUserRepository userRepo, RAFYCContext context)
{
_userRepo = userRepo;
_userRepo.SetDbContext(context);
}
}
public class UserRepository : IUserRepository
{
public RAFYCContext _context;
public UserRepository() { }
public void SetDbContext(RAFYCContext context)
{
this._context = context;
}
}
这个方法可以正常工作,但是我想将DbContext注入到我的仓库构造函数中,而不是在实例化后在控制器构造函数中进行分配,如下所示:
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
IUserRepository _userRepo;
public UserController(IUserRepository userRepo)
{
_userRepo = userRepo;
}
}
public class UserRepository : IUserRepository
{
RAFYCContext _context;
public UserRepository(RAFYCContext context)
{
_context = context;
}
}
使用该代码会出现以下错误:
InvalidOperationException: 无法从单例“RAFYC.MobileAppService.Repositories.IUserRepository”中消费作用域服务 'RAFYC.MobileAppService.Models.RAFYCContext'
请问在ASP.NET Core(2.2)中是否可能实现此操作?