首页 > 解决方案 > Asp.net Core Mvc DI

问题描述

如果我有接口,我想了解它是如何工作的

public interface IProductRepository
{
    IQueryable<Product> Products { get; }
}

然后我有一个实现这个接口的类

public class EFProductRepository : IProductRepository
{
    public EFProductRepository(ApplicationDBContext ctx)
    {
        context = ctx;
    }
    private ApplicationDBContext context;

    public IQueryable<Product> Products => context.Products;
}

ApplicationDbContext 类是

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options) { }
    public DbSet<Product> Products { get; set; }

}

ConfigurationServices 方法是

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDBContext>(options =>
    {
        options.UseSqlServer(Configuration["Data:SportStoreProducts:Connectionstring"]);
    });
    services.AddTransient<IProductRepository, EFProductRepository>();
    services.AddMvc();
}

在搜索了它的工作原理后,我发现当使用services.AddTransient<IProductRepository, EFProductRepository>();应用程序中使用接口的组件时,它们会在创建时IProductRepository收到一个对象。EFProductRepository但是我想了解当EFProductRepository通过此服务创建类对象时,构造函数EFProductRepository需要ApplicationDBContext类对象在这种情况下使用什么技术?

标签: c#asp.net-coredependency-injectionentity-framework-core

解决方案


推荐阅读