Wiki

Clone wiki

DryIoc / Home

<!--Auto-generated from .cs file, the edits here will be lost! -->

Wiki Home

Getting Started

Let's define a simple interface and implementation setup:

// these usings are for later
using DryIoc;
using NUnit.Framework;
// ReSharper disable UnusedVariable

public interface IService { }
public class SomeService : IService { }

// A client consuming the `IService` dependency
public interface IClient
{
    IService Service { get; }
}

public class SomeClient : IClient
{
    public IService Service { get; }
    public SomeClient(IService service) { Service = service; }
} 

To illustrate the idea of Dependency Injection container, we will start from the problem. Let's create SomeClient by hand, but with DI principle in mind:

class Created_manually
{
    [Test]
    public void Example()
    {
        IClient client = new SomeClient(new SomeService());
    }
} 

The manual implementation is a hard-wired - we are using implementation types SomeClient and SomeService in-place of creation of IClient. What if we need to change SomeService to the TestService later, may be after the code for IClient creation is compiled. To enable such scenario, we need a kind of configuration what interface is implemented by what type. The configuration should be decoupled from actual creation code, in order to be changed independently.

Here goes the DI / IoC container!

Let's try DryIoc:

class Created_by_DryIoc
{
    private IContainer _container;

    [SetUp]
    public void Configure_types()
    {
        _container = new Container();
        _container.Register<IClient, SomeClient>();
        _container.Register<IService, SomeService>();
    }

    [Test]
    public void Create_client()
    {
        var client = _container.Resolve<IClient>();
        Assert.IsInstanceOf<SomeClient>(client);
    }
} 

In the example with DryIoc, configuration of types is separate from the resolution, so that both can be changed independently.

Now we have a configurator and creator Container, the provider of the service instances for our program. Given that container controls the creation, we may logically extend it further to control the lifetime as well.

Summarizing, DI / IoC container is the tool to enforce Open-Closed principle and to support extensibility and testability of our code.

User's Guide

Companions

Extensions

Samples

Located in this repo:

External links:

Latest Version

Get from NuGet:

  • DryIoc.dll NuGet Badge
  • DryIoc (source code) NuGet Badge
  • DryIoc.Internal (source code with public types made internal) NuGet Badge

v4.1.2 / 2020-03-12

Release Notes

Previous Versions

Updated