Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Simplify.DI

Alexanderius edited this page Sep 1, 2014 · 23 revisions

Provides DIContainer.Current ambient context as centralized IOC container. Provides Interfaces for creation IOC container providers(wrappers).

Using DIContainer.Current and respective container provider you can switch between any IOC container without rewriting your code. Also as a centralized IOC container you can use it for building, for example, some framework which needs to use constructor injection and at the same time use it by that framework user (example using it in framework).

Available at NuGet as binary package

By default DIContainer.Current initialized with DryIocDIProvider container provider (Unstable!)

Another container providers available:

Main IOC container interface is IDIContainerProvider

Examples

Entities

public interface IFoo
{		
}

public class Foo : IFoo
{
	public Foo(IBar bar)
	{			
	}
}

public class Foo2 : IFoo
{
	public Foo2(IBar bar, string someParameter)
	{
	}
}

public interface IBar
{		
}

public class Bar : IBar
{		
}

public class Bar2 : IBar
{
	public Bar2(string someParameter)
	{			
	}
}

Registration

// Simple registration
DIContainer.Current.Register<IBar, Bar>();
DIContainer.Current.Register<IFoo, Foo>();

// Registration with delegate
DIContainer.Current.Register<IBar>(p => new Bar2("test"));

Resolve

var myObj = DIContainer.Current.Resolve<IBar>();

Scopes

3 type of scopes available:

  • Singleton (default scope) only one instance will be created be container
  • Transient, new instance will be created on every Resolve request
  • PerLifetimeScope, only one instance will be created for current lifetime scope

Using PerLifetimeScope scope

Lifetime scope registration
// Simple registration
DIContainer.Current.Register<IBar, Bar>(LifetimeType.PerLifetimeScope);

// Any dependency while registration with delegate should be resolved with delegate parameter `p`, it is current scope resolve provider.
DIContainer.Current.Register<IFoo>(p => new Foo2(p.Resolve<IBar>(), "Test"), LifetimeType.PerLifetimeScope);
Lifetime scope usage
// Note, what scope.Container actually it is the same container as DIContainer.Current, for example, if using SimpleInjector, but with DryIoc it will be child container provider.
using (var scope = DIContainer.Current.BeginLifetimeScope())
{
	var myObject = scope.Container.Resolve<IFoo>();
}

Registration specific to IOC container

You can use any IOC container to directly register types or perform specific actions, for example, with Simple Injector:

var container = new SimpleInjector.Container();
container.RegisterSingle<SimpleInjectorDIProvider>();
container.Verify();
	
var provider = new SimpleInjectorDIProvider();
provider.Container = _container;
DIContainer.Current = provider;
Clone this wiki locally