using System;
using System.Linq;
using SimpleInjector;
namespace Tapeti.SimpleInjector
{
///
/// Dependency resolver and container implementation for SimpleInjector.
///
public class SimpleInjectorDependencyResolver : IDependencyContainer
{
private readonly Container container;
private readonly Lifestyle defaultsLifestyle;
private readonly Lifestyle controllersLifestyle;
///
///
public SimpleInjectorDependencyResolver(Container container, Lifestyle defaultsLifestyle = null, Lifestyle controllersLifestyle = null)
{
this.container = container;
this.defaultsLifestyle = defaultsLifestyle;
this.controllersLifestyle = controllersLifestyle;
}
///
public T Resolve() where T : class
{
return container.GetInstance();
}
///
public object Resolve(Type type)
{
return container.GetInstance(type);
}
///
public void RegisterDefault() where TService : class where TImplementation : class, TService
{
if (!CanRegisterDefault())
return;
if (defaultsLifestyle != null)
container.Register(defaultsLifestyle);
else
container.Register();
}
///
public void RegisterDefault(Func factory) where TService : class
{
if (!CanRegisterDefault())
return;
if (defaultsLifestyle != null)
container.Register(factory, defaultsLifestyle);
else
container.Register(factory);
}
///
public void RegisterDefaultSingleton() where TService : class where TImplementation : class, TService
{
if (CanRegisterDefault())
container.RegisterSingleton();
}
///
public void RegisterDefaultSingleton(TService instance) where TService : class
{
if (CanRegisterDefault())
container.RegisterInstance(instance);
}
///
public void RegisterDefaultSingleton(Func factory) where TService : class
{
if (CanRegisterDefault())
container.RegisterSingleton(factory);
}
///
public void RegisterController(Type type)
{
if (controllersLifestyle != null)
container.Register(type, type, controllersLifestyle);
else
container.Register(type);
}
private bool CanRegisterDefault() where TService : class
{
// ReSharper disable once SimplifyLinqExpression - not a fan of negative predicates
return !container.GetCurrentRegistrations().Any(ip => ip.ServiceType == typeof(TService));
}
}
}