ASP.Net Core中的依赖注入

问题描述 投票:0回答:2

一直在使用ASP.NET Core做一些示例代码,试图了解它是如何组合在一起的,我很难过为什么我无法成功解析服务。

configure服务方法可以调用添加ISeedDataService

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddDbContext<CustomerDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped<ICustomerDbContext, CustomerDbContext>();
    services.AddScoped<ICustomerRepository, CustomerRepository>();
    services.AddScoped<ISeedDataService, SeedDataService>();
}

在Configure中,我调用AddSeedData(),如下所示

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.AddSeedData();
}

这是调用下面的扩展方法

public static async void AddSeedData(this IApplicationBuilder app)
{
    var seedDataService = app.ApplicationServices.GetRequiredService<ISeedDataService>();
    await seedDataService.EnsureSeedData();
}

并且SeedDataService在下面

public class SeedDataService : ISeedDataService
{
    private ICustomerDbContext _context;
    public SeedDataService(ICustomerDbContext context)
    {
        _context = context;
    }

    public async Task EnsureSeedData()
    {
        _context.Database.EnsureCreated();

        _context.Customers.RemoveRange(_context.Customers);
        _context.SaveChanges();

        Customer customer = new Customer();
        customer.FirstName = "Chuck";
        customer.LastName = "Norris";
        customer.Age = 30;
        customer.Id = Guid.NewGuid();

        _context.Add(customer);

        Customer customer2 = new Customer();
        customer2.FirstName = "Fabian";
        customer2.LastName = "Gosebrink";
        customer2.Age = 31;
        customer2.Id = Guid.NewGuid();

        _context.Add(customer2);

        await _context.SaveChangesAsync();
    }
}

完全不确定我做错了什么,错误是System.InvalidOperationException:'无法从根提供程序解析作用域服务'secondapp.Services.ISeedDataService'。

c# asp.net-core dependency-injection
2个回答
2
投票

您(并且应该)将ISeedDataService添加为范围服务。但是,您试图从没有作用域的根服务提供程序(例如app.ApplicationServices)解析它。这意味着从中有效解析的作用域服务将转换为单例服务,并且在应用程序关闭之前不会处理,否则将导致错误。

这里的解决方案是自己创建一个范围:

public void Configure(IApplicationBuilder app)
{
    using (var scope = app.ApplicationServices.CreateScope())
    {
        var seedDataService = scope.ServiceProvider.GetRequiredService<ISeedDataService>();
        // Use seedDataService here
    }
}

请查看有关依赖注入范围的at the documentation


在第二个注释:你的AddSeedData扩展方法是async void,你不是在等待结果。您应该返回一个任务(async Task)调用AddSeedData().GetAwaiter().GetResult()以确保阻止直到播种完成。


-1
投票

Configure()方法允许参数依赖注入,因此您可以执行以下操作。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ISeedDataService seedService)
{
    seedService.EnsureSeedData().Wait(); // Configure() is not async so you have to wait
}
© www.soinside.com 2019 - 2024. All rights reserved.