![](/img/trans.png)
[英]Established dependency injection in .NET Core Console Application for EF Core DbContext Service Error
[英]EF core DbContext with dependency injection
我创建了一个可注入的 dbcontext
启动.cs:
public void ConfigureServices(IServiceCollection services) {
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddDbContext<DBContext>(options => options.UseSqlServer("Server=localhost;Database=mydb;Trusted_Connection=True;"));
}
工作单位:
public class UnitOfWork : IUnitOfWork {
private readonly DBContext _context;
public UnitOfWork(DBContext context) {
_context = context;
}
控制器中的注入工作正常:
public class UserController : ControllerBase {
private readonly IUnitOfWork unitOfWork;
public UserController(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
如何创建在构造函数中使用 IUnitOfWork 并从主程序调用它的自定义类?
自定义类:
public class CustomClass {
private readonly IUnitOfWork unitOfWork;
public CustomClass(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
主程序:
public class Program {
public static void Main(string[] args) {
var unitOfWork=new UnitOfWork() // Here I don't want to pass new DBContext I want to reach the same injected DBContext
var customClass =new CustomClass (unitOfWork);
}
}
首先,将你的代码从ConfigureServices
移到一些可以被 Web 和控制台项目使用的共享库中。 创建扩展方法来配置您的所有服务。
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleApp13
{
public static class ConfigureServicesExtensions
{
public static void ConfigureMyServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddDbContext<ApplicationDbContext>();
serviceCollection.AddScoped<IUnitOfWork, UnitOfWork>();
serviceCollection.AddScoped<CustomClass>();
}
}
}
这是您的控制台应用程序的外观
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleApp13
{
class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.ConfigureMyServices();
using var serviceProvider = serviceCollection.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var myService = scope.ServiceProvider.GetService<CustomClass>();
}
}
}
还有你的网络项目
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureMyServices();
}
您可以做的只是将您的类添加到依赖注入容器并将其注入到您的构造函数中,您不需要在控制器中注入 IUnitOfWork。
services.AddScoped<CustomClass>();
然后在您的控制器构造函数中
public class UserController : ControllerBase {
private readonly CustomClass _CustomClass;
public UserController(CustomClass customClass) {
_CustomClass = customClass;
}
}
之后你就可以在你的类方法中使用这个类
我会尝试这样的事情:
public class Program {
public static void Main(string[] args) {
var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
optionsBuilder.UseSqlServer(connectionstring);
using(DbContext dbContext = new DbContext(optionsBuilder.Options))
{
var unitOfWork=new UnitOfWork(dbContext)
var customClass =new CustomClass (unitOfWork);
.....
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.