2016-12-05 07:00:09 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
2016-11-20 13:34:50 +00:00
|
|
|
|
using System.Reflection;
|
|
|
|
|
using SimpleInjector;
|
|
|
|
|
using Tapeti.Annotations;
|
|
|
|
|
using Tapeti.Default;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
|
|
|
|
namespace Tapeti.SimpleInjector
|
|
|
|
|
{
|
2016-12-05 07:00:09 +00:00
|
|
|
|
public class SimpleInjectorDependencyResolver : IDependencyResolver, IDependencyInjector
|
2016-11-20 13:34:50 +00:00
|
|
|
|
{
|
|
|
|
|
private readonly Container container;
|
|
|
|
|
|
|
|
|
|
public SimpleInjectorDependencyResolver(Container container, bool registerDefaults = true)
|
|
|
|
|
{
|
|
|
|
|
this.container = container;
|
|
|
|
|
|
|
|
|
|
if (registerDefaults)
|
|
|
|
|
RegisterDefaults();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T Resolve<T>() where T : class
|
|
|
|
|
{
|
|
|
|
|
return container.GetInstance<T>();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2016-12-05 07:00:09 +00:00
|
|
|
|
public void RegisterPublisher(IPublisher publisher)
|
|
|
|
|
{
|
|
|
|
|
IfUnregistered<IPublisher>(container.GetCurrentRegistrations(), () => container.RegisterSingleton(publisher));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public void RegisterController(Type type)
|
|
|
|
|
{
|
|
|
|
|
container.Register(type);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2016-11-20 13:34:50 +00:00
|
|
|
|
public SimpleInjectorDependencyResolver RegisterDefaults()
|
|
|
|
|
{
|
|
|
|
|
var currentRegistrations = container.GetCurrentRegistrations();
|
|
|
|
|
|
|
|
|
|
IfUnregistered<IControllerFactory, SimpleInjectorControllerFactory>(currentRegistrations);
|
|
|
|
|
IfUnregistered<IMessageSerializer, DefaultMessageSerializer>(currentRegistrations);
|
|
|
|
|
IfUnregistered<IRoutingKeyStrategy, DefaultRoutingKeyStrategy>(currentRegistrations);
|
|
|
|
|
|
|
|
|
|
return this;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2016-12-05 07:00:09 +00:00
|
|
|
|
private void IfUnregistered<TService, TImplementation>(IEnumerable<InstanceProducer> currentRegistrations) where TService : class where TImplementation: class, TService
|
2016-11-20 13:34:50 +00:00
|
|
|
|
{
|
2016-12-05 07:00:09 +00:00
|
|
|
|
// ReSharper disable once SimplifyLinqExpression - not a fan of negative predicates
|
|
|
|
|
if (!currentRegistrations.Any(ip => ip.ServiceType == typeof(TService)))
|
|
|
|
|
container.Register<TService, TImplementation>();
|
2016-11-20 13:34:50 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-05 07:00:09 +00:00
|
|
|
|
private void IfUnregistered<TService>(IEnumerable<InstanceProducer> currentRegistrations, Action register) where TService : class
|
2016-11-20 13:34:50 +00:00
|
|
|
|
{
|
|
|
|
|
// ReSharper disable once SimplifyLinqExpression - not a fan of negative predicates
|
|
|
|
|
if (!currentRegistrations.Any(ip => ip.ServiceType == typeof(TService)))
|
2016-12-05 07:00:09 +00:00
|
|
|
|
register();
|
2016-11-20 13:34:50 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|