使用 DI 实现 Repository 和 Db Context .Net Core Console Entity Framework
Implement Repository and Db Context .Net Core Console Entity Framework with DI
我正在创建 .NET Core 6 控制台应用程序。
我有一个实现接口 IStorageCompetitorRepository
.
的存储库 class StorageCompetitorRepository
当我尝试初始化时,以下内容在 Program.cs
中中断并显示为 null:
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
StorageCompetitorRepository
class通过构造函数初始化DbContext
Program.cs
:
using Microsoft.Extensions.DependencyInjection;
class Program
{
private static StorageCompetitorRepository _storageCompetitorRepository;
static void Main(string[] args)
{
// configure services
var services = new ServiceCollection()
.AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
// create service provider
var serviceProvider = services.BuildServiceProvider();
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
bool runLoaderTool = true;
while (runLoaderTool)
{
runLoaderTool = ChooseElasticIndexMenu(runLoaderTool, _storageCompetitorRepository);
}
}
public static bool ChooseElasticIndexMenu(bool runLoaderTool, StorageCompetitorRepository storageCompetitorRepository)
{
// didn't add the full code that returns the boolean all you need
// to know that the repo class method is called here
storageCompetitorRepository.GetStorageCompetitors();
}
}
StorageCompetitorRepository
:
public class StorageCompetitorRepository : IStorageCompetitorRepository
{
string DatabaseServer = ConfigurationManager.AppSettings["DataBaseServer"];
private readonly DevModelContext _devModelContext;
public StorageCompetitorRepository(DevModelContext devModelContext) => _devModelContext = devModelContext;
public List<storage_competitor> GetStorageCompetitors()
{
try
{
var ctx = _devModelContext.StorageCompetitors;
var storageCompetitorList = (from sc in ctx
where sc.active == true && sc.id_period == (from s in ctx select s).Max(s => s.id_period)
select sc).Distinct()
.OrderBy(sc => sc).ToList();
var countStorageCompetitors = storageCompetitorList.Count();
Console.WriteLine($"{countStorageCompetitors} Storage Competitors were found in SQL Server : {DatabaseServer} Database : Competitors");
return storageCompetitorList;
}
catch
{
return new List<storage_competitor>();
}
}
}
DevModelContext
:
public class DevModelContext : DbContext
{
string connectionString = ConfigurationManager.ConnectionStrings["connCompetitorsDev"].ConnectionString;
public DevModelContext(DbContextOptions<DevModelContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString);
}
public DbSet<storage_competitor> StorageCompetitors { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<storage_competitor>().ToTable("storage_competitor");
}
}
为什么我对 repo class 的初始化在将其添加为临时服务时显示为 null?
如有任何想法或建议,我们将不胜感激。
您注册的是接口,要求具体实现
你说的是“解析 IStorageCompetitorRepository 时,给我 StorageCompetitorRepository”
var services = new ServiceCollection()
.AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
后来你想解决repository的具体实现,DI找不到,因为它只是作为接口注册到容器中,有意义吗?
改变这个:
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
为此:
_storageCompetitorRepository = serviceProvider.GetService<IStorageCompetitorRepository>();
如果你想能够解决具体的实现,你需要注册它。
AddTransient<StorageCompetitorRepository>();
如果你也想通过接口解析它,你也可以像这样将它注册为接口。
AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
或
AddTransient<IStorageCompetitorRepository>(x => x.GetRequiredService<StorageCompetitorRepository);
我正在创建 .NET Core 6 控制台应用程序。
我有一个实现接口 IStorageCompetitorRepository
.
StorageCompetitorRepository
当我尝试初始化时,以下内容在 Program.cs
中中断并显示为 null:
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
StorageCompetitorRepository
class通过构造函数初始化DbContext
Program.cs
:
using Microsoft.Extensions.DependencyInjection;
class Program
{
private static StorageCompetitorRepository _storageCompetitorRepository;
static void Main(string[] args)
{
// configure services
var services = new ServiceCollection()
.AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
// create service provider
var serviceProvider = services.BuildServiceProvider();
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
bool runLoaderTool = true;
while (runLoaderTool)
{
runLoaderTool = ChooseElasticIndexMenu(runLoaderTool, _storageCompetitorRepository);
}
}
public static bool ChooseElasticIndexMenu(bool runLoaderTool, StorageCompetitorRepository storageCompetitorRepository)
{
// didn't add the full code that returns the boolean all you need
// to know that the repo class method is called here
storageCompetitorRepository.GetStorageCompetitors();
}
}
StorageCompetitorRepository
:
public class StorageCompetitorRepository : IStorageCompetitorRepository
{
string DatabaseServer = ConfigurationManager.AppSettings["DataBaseServer"];
private readonly DevModelContext _devModelContext;
public StorageCompetitorRepository(DevModelContext devModelContext) => _devModelContext = devModelContext;
public List<storage_competitor> GetStorageCompetitors()
{
try
{
var ctx = _devModelContext.StorageCompetitors;
var storageCompetitorList = (from sc in ctx
where sc.active == true && sc.id_period == (from s in ctx select s).Max(s => s.id_period)
select sc).Distinct()
.OrderBy(sc => sc).ToList();
var countStorageCompetitors = storageCompetitorList.Count();
Console.WriteLine($"{countStorageCompetitors} Storage Competitors were found in SQL Server : {DatabaseServer} Database : Competitors");
return storageCompetitorList;
}
catch
{
return new List<storage_competitor>();
}
}
}
DevModelContext
:
public class DevModelContext : DbContext
{
string connectionString = ConfigurationManager.ConnectionStrings["connCompetitorsDev"].ConnectionString;
public DevModelContext(DbContextOptions<DevModelContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString);
}
public DbSet<storage_competitor> StorageCompetitors { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<storage_competitor>().ToTable("storage_competitor");
}
}
为什么我对 repo class 的初始化在将其添加为临时服务时显示为 null?
如有任何想法或建议,我们将不胜感激。
您注册的是接口,要求具体实现
你说的是“解析 IStorageCompetitorRepository 时,给我 StorageCompetitorRepository”
var services = new ServiceCollection()
.AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
后来你想解决repository的具体实现,DI找不到,因为它只是作为接口注册到容器中,有意义吗? 改变这个:
_storageCompetitorRepository = serviceProvider.GetService<StorageCompetitorRepository>();
为此:
_storageCompetitorRepository = serviceProvider.GetService<IStorageCompetitorRepository>();
如果你想能够解决具体的实现,你需要注册它。
AddTransient<StorageCompetitorRepository>();
如果你也想通过接口解析它,你也可以像这样将它注册为接口。
AddTransient<IStorageCompetitorRepository, StorageCompetitorRepository>();
或
AddTransient<IStorageCompetitorRepository>(x => x.GetRequiredService<StorageCompetitorRepository);