【问题标题】:Call method in class using dependency injection使用依赖注入在类中调用方法
【发布时间】:2020-04-21 15:21:08
【问题描述】:

我有一个 .NET 核心网络应用程序,它设置了依赖项:

    public class FooController : Controller
    {
        private readonly IFooRepository FooRepository;

        public FooController(IFooRepository fooRepository)
        {
            FooRepository = fooRepository;
        }
    }

    public class FooRepository : IFooRepository
    {
        private readonly IFooContext FooContext;

        public FooRepository(IFooContext fooContext)
        {
            FooContext = fooContext;
        }
    }

    public class FooContext : BaseContext, IFooContext
    {
        public FooContext(ApplicationDbContext appDbContext) : base(appDbContext)
        {
        }
    }

一切正常。

我想要做的是创建一个类,它调用 FooRepository 中的一个方法,而不在构造函数中使用 IFooRepository,这可能吗?:

  public class Bar
    {
        public Bar()
        {
             FooRepository.GetMyFoo();
        }
    }

【问题讨论】:

  • 你希望它做什么?你可以有一个静态方法。但我怀疑这是否有意义?
  • 不使用静态(紧耦合),这违背了使用 DI 的全部目的。
  • 这可能是XY problem
  • 我看到的 CTOR 注入和静态方法之外的唯一其他选项是 a) 使用 new 创建一个新实例或 b) 从您选择的 DI 容器中解析一个实例。两者都不如CTOR注射(如果a)是可能的)。
  • IF 这是关于不将完整的IFooRepository 接口放弃给Bar,为什么不让 FooRepository 实现另一个接口并将其连接到 DI 中,然后注入那个接口?

标签: c# .net-core dependency-injection


【解决方案1】:

只需为您要“共享”的方法创建另一个接口。 并且不要忘记将此接口实现也添加到您的 DI 容器中。

现在你的IFooRepository 没有GetMyFoo() 并且IGetMyFooAble 的消费者不知道比他需要的更多。

public class FooController : Controller
{
    private readonly IGetMyFooAble FooRepository;

    public FooController(IGetMyFooAble fooRepository)
    {
        FooRepository = fooRepository;
        fooRepository.GetMyFoo();
    }
}

public class FooRepository : IFooRepository, IGetMyFooAble
{
    private readonly IFooContext FooContext;

    public FooRepository(IFooContext fooContext)
    {
        FooContext = fooContext;
    }

    public void GetMyFoo() { /* your stuff */ }
}


public interface IGetMyFooAble
{
    public void GetMyFoo();
}

public class FooContext : BaseContext, IFooContext
{
    public FooContext(ApplicationDbContext appDbContext) : base(appDbContext)
    {
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2022-01-02
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多