如何使用接受 DbContext 作为 asp.net 核心参数的依赖注入来传递 class

How to pass class using Dependency Injection that accept DbContext as a parameter in asp.net core

我有 class UnitOFWork 接受上下文 class 作为参数,那么我如何使用依赖注入[= 传递这个 class 13=]

这是我的 classes

public class UnitOfWork
{
    public Context context;

    public UnitOfWork(Context context)
    {
        this.context = context;
    }
}

 public class Context : DbContext
 {
     public Context(DbContextOptions<Context> options) : base(options)
     {
     }
 }

那么如何使用依赖注入来传递 unitofwork class 的实例。 谢谢!

在您的 ConfigureServices 方法中(通常在 Startup 或 Program 中,具体取决于您的项目),定义服务。

services.AddScoped<Context>();
services.AddScoped<UnitOfWork>();

当构造一个 class 请求类型为 UnitOfWork 的参数时,依赖注入器将构造 UnitOfWork - 为此它还将构造 Context .新创建的 UnitOfWork 实例将被传递到下一个 class。

public class DoesWork
{
    UnitOfWork _unit;
    public DoesWork(UnitOfWork unit)
    {
        _unit = unit;
    }
    public void Work()
    {
        Console.WriteLine("A non-null unit was passed in: {0}.", _unit != null);
    }
}

通常要获得一个 class 实际执行某些操作,您需要在 Startup/Program 文件中使用如下方法:services.AddHostedService<UnitOfWorkWorkerService>()。 ASP.Net 中的 services.AddControllersWithViews() 核心将为您的所有控制器 class 做类似的事情。 并且在某个地方有一个 class 可以使用你的 DI 生成的 classes。 worker 服务 class 将在 Main() 中构造,在 CreateHostBuilder() 中。

public class UnitOfWorkWorkerService : BackgroundService
{
    public UnitOfWorkWorkerService(DoesWork fromDependencyInjection)
    {
        _doesWork = fromDependencyInjection;
    }
    private readonly DoesWork _doesWork;
    // This method will be called when your application is started.
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _doesWork.Work();
            await Task.Delay(1000, stoppingToken);
        }
    }
}

请注意,这些示例源自我拥有的托管服务应用程序,它们在概念上相似但比 ASP.Net 核心应用程序等更简单。