.Net - 根据数据库类型有条件地注入服务

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

目前我正在开发一个项目,需要能够将数据保存在不同的数据库类型中(PostgresMongoDb

考虑到这一点,我考虑将我的存储库逻辑抽象到某些接口中,这种方式对于我正在使用的数据库类型的业务逻辑并不重要。这样我就可以编写逻辑,而无需关心存储库将如何实现它的逻辑。

但是我该如何注射呢?

我的意思是,想象一下:

  • Postgres 中,我将使用 Guid 作为 id 类型
  • MongoDb 我将使用 ObjectId 作为 Id 类型

仅出于示例目的,我将在控制器文件中添加所有内容,这样很容易表示它

[ApiController]
[Route("[controller]")]
public class ExampleController : Controller
{
    private readonly IExampleRepository<> _exampleRepository;

    public ExampleController(IExampleRepository<> exampleRepository)
    {
        _exampleRepository = exampleRepository;
    }
    [HttpGet]
    public IActionResult Index()
    {
        return Ok();
    }
}
public class ExampleEntity<TId>
{
    public TId? Id { get; set; }
    public string? Description { get; set; }
}

public interface IRepositoryWithId<T, in TIdType>
{
    Task<bool> ExistsAsync(TIdType id, CancellationToken cancellationToken = default);
    Task<T?> GetByIdAsync(TIdType id, CancellationToken cancellationToken = default);
}
public interface IExampleRepository<TId> : IRepositoryWithId<ExampleEntity<TId>, TId>
{

}
public class MongoRepository : IExampleRepository<ObjectId>
{
    public Task<bool> ExistsAsync(ObjectId id, CancellationToken cancellationToken = default) => Task.FromResult(true);
    public Task<ExampleEntity<ObjectId>?> GetByIdAsync(ObjectId id, CancellationToken cancellationToken = default) => Task.FromResult(null as ExampleEntity<ObjectId>);
}
public class PostgresRepository : IExampleRepository<ObjectId>
{
    public Task<bool> ExistsAsync(ObjectId id, CancellationToken cancellationToken = default) => Task.FromResult(true);
    public Task<ExampleEntity<ObjectId>?> GetByIdAsync(ObjectId id, CancellationToken cancellationToken = default) => Task.FromResult(null as ExampleEntity<ObjectId>);
}

也许我不知道如何搜索它,抱歉,如果这是一个重复的问题。

c# dependency-injection domain-driven-design .net-7.0
1个回答
0
投票

但是我该如何注射呢?
是的,它基于定义的配置。根据环境需要部署它。

那就简单了。只需读取配置值并注册所需的内容即可。对于最小托管模型(网络应用程序的 .NET 7 中的默认值),它可能如下所示:

var dbType = builder.Configuration.GetValue<string>("DbSettings:Type");
switch (dbType)
{
    case "Mongo":
        // deps for MongoRepository
        builder.Services.AddScoped<IExampleRepository<ObjectId>, MongoRepository>();
        break;
    case "PostgreSQL":
    default:
        // deps for PostgresRepository
        builder.Services.AddScoped<IExampleRepository<ObjectId>, PostgresRepository>();
        break;
}
© www.soinside.com 2019 - 2024. All rights reserved.