如何使用泛型类型作为方法参数

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

我想在我的应用程序中注册多个

DbContext
,以尝试使其更加模块化。然而,许多必要的调用并不重复,例如

    builder.Services.AddDbContext<DbContext1>((_, options) =>
    {
        // some configuration
    }, ServiceLifetime.Transient);
    builder.Services.AddDbContext<DbContext2>((_, options) =>
    {
        // the exact same configuration
    }, ServiceLifetime.Transient);

唯一不同的是 DbContext 类,对于测试设置、迁移等都是如此。

我希望能够选择每次都能够迭代所有 DbContext,这样我就不太可能忘记注册一个。像这样的东西:

public static void DoWithEachRegisteredDbContext(DoWithDbContext<> magic)
{
    magic<DbContext1>();
    magic<DbContext2>();
}

public delegate Type[] DoWithDbContext<TContext>();

// and this method is called like this for the above example

DoWithEachRegisteredDbContext(AddDbContext);

public Type[] AddDbContext<TContext>() {
    builder.Services.AddDbContext<TContext>((_, options) =>
    {
        // some configuration
    }, ServiceLifetime.Transient);
}

这样的事情可能吗?怎么办?

c#
1个回答
0
投票

如果我正确理解了这个问题,那么您正在寻找的是减少冗余代码,并且保持方法接近更改,但对扩展开放

有一个 SOLID 原则 正是围绕这一点,它被称为 开闭原则 (SOLID 中的“O”),它是帮助我们准确解决这些用例的原则。

解决这个问题的一种方法是使用字典之类的东西,迭代实例中的每个 DbContext 并仅向该数据库添加新上下文, 然而,这听起来并不是最优雅的解决方案。

我建议深入研究 OCP 并检查它提供的解决方案,因为这更像是一个有问题的设计选择,可以通过多种不同的方式真正解决。

如果你对 SOLID 不够熟悉,我强烈建议你更好地学习它。

祝你好运! :)

© www.soinside.com 2019 - 2024. All rights reserved.