且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

任何地方的固体原理示例?

更新时间:2022-12-09 13:36:07

查看 Mark Seeman 的博客,或者购买他的书更好.它涵盖的不仅仅是 DI.我很感激您可能只想要一个简单的示例来开始使用.然而,这是一个许多声称自己了解的主题,因此值得好好学习.

Have a look at Mark Seeman's blog or, even better, buy his book. It covers so much more than just DI. I appreciate you probably just want a simple sample to get going with. However, it's a subject that many who claim to understand don't and therefore worth learning well.

也就是说,这是一个非常简单的例子.我所理解的术语是控制反转依赖注入.控制反转指的是您将类的依赖项的控制权交给其他某个类,这与控制依赖项本身的类相反,通常是通过 new 关键字.这种控制是通过依赖注入来实现的,其中一个类被赋予或注入它的依赖项.这可以通过 IoC 框架或代码(称为 Pure DI).注入可以在类的构造函数中执行,通过属性或作为方法的参数.依赖可以是任何类型,它们不必是抽象的.

That said, here's a very simple example. The terminology, as I understand it, is Inversion of Control and Dependency Injection. Inversion of Control refers to the fact that you give control of a class's dependencies to some other class, opposed to the class controlling the dependency itself, usually via the new keyword. This control is exerted via Dependency Injection where a class is given, or injected, with its dependencies. This can be done via an IoC framework or in code (known as Pure DI). Injection can be performed in the class's constructor, via a property or as a method's parameter. Dependencies can be any type, they don't have to be abstract.

这是一个列出未掺杂的环法自行车赛冠军的课程:

Here's a class that lists Tour de France winners who haven't doped:

class CleanRiders
{
    List<Rider> GetCleanRiders()
    {
        var riderRepository = new MsSqlRiderRepository();

        return riderRepository.GetRiders.Where(x => x.Doping == false);
    }
}

这个类依赖于MsSqlRiderRepository.该类控制实例的创建.问题是这种依赖是不灵活的.很难将其更改为 OracleRiderRepositoryTestRiderRepository.

This class is dependent on the MsSqlRiderRepository. The class takes control of the creation of the instance. The problem is that this dependency is inflexible. It's hard to change it to a OracleRiderRepository or a TestRiderRepository.

IoC 和 DI 为我们解决了这个问题:

IoC and DI solve this for us:

class CleanRiders
{
    private IRiderRepository _repository;

    public CleanRiders(IRiderRepository repository)
    {
        _repository = repository;
    }

    List<Rider> GetCleanRiders()
    {
        return _repository.GetRiders.Where(x => x.Doping == false);
    }
}

现在这个类只依赖于一个接口.依赖项的控制权已交给类的创建者,必须通过其构造函数注入:

Now the class is only depending on an Interface. Control of the dependency has been given up to the class's creator and must be injected via its constructor:

void Main()
{
    var c = new CleanRiders(new MsSqlRepository());

    var riders = c.GetRiders();
}

可以说是一种更灵活、可测试和可靠的方法.

Arguably, a more flexible, testable and SOLID approach.