Let's define a simple interface and implementation setup:
namespace DryIoc.Docs;
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, the configuration of types is separate from the resolution so that both can be changed independently.
Now we have the configured Container - the provider of the service instances for our program. Given that container controls the creation of the services we may logically extend it responsibilities further to control the lifetime as well.
Summarizing, DI/IoC container is the tool to enforce Open-Closed principle and to support the extensibility and testability of the code.
-
Interesting topics:
-
FAQs
-
ASP.NET:
-
OWIN:
Located in this repo in the [samples]((https://github.com/dadhi/DryIoc/tree/master/samples) folder.
Get from NuGet: