Radarr/NzbDrone.Common/Composition/ContainerBuilderBase.cs

95 lines
2.9 KiB
C#
Raw Normal View History

2013-04-20 00:05:48 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NzbDrone.Common.Messaging;
using NzbDrone.Common.Reflection;
2013-05-10 23:53:50 +00:00
using TinyIoC;
2013-04-20 00:05:48 +00:00
2013-05-10 23:53:50 +00:00
namespace NzbDrone.Common.Composition
2013-04-20 00:05:48 +00:00
{
public abstract class ContainerBuilderBase
{
private readonly List<Type> _loadedTypes;
2013-05-10 23:53:50 +00:00
public IContainer Container { get; private set; }
2013-04-20 00:05:48 +00:00
protected ContainerBuilderBase(params string[] assemblies)
{
2013-05-10 23:53:50 +00:00
Container = new Container(new TinyIoCContainer());
2013-04-20 00:05:48 +00:00
_loadedTypes = new List<Type>();
foreach (var assembly in assemblies)
{
_loadedTypes.AddRange(Assembly.Load(assembly).GetTypes());
}
AutoRegisterInterfaces();
}
private void AutoRegisterInterfaces()
{
2013-05-10 23:53:50 +00:00
var loadedInterfaces = _loadedTypes.Where(t => t.IsInterface).ToList();
var implementedInterfaces = _loadedTypes.SelectMany(t => t.GetInterfaces()).Where(i => !i.Assembly.FullName.StartsWith("System")).ToList();
2013-04-20 00:05:48 +00:00
2013-05-10 23:53:50 +00:00
var contracts = loadedInterfaces.Union(implementedInterfaces).Where(c => !c.IsGenericTypeDefinition && !string.IsNullOrWhiteSpace(c.FullName))
.Except(new List<Type> { typeof(IMessage), typeof(ICommand), typeof(IEvent), typeof(IContainer) }).Distinct().OrderBy(c => c.FullName);
2013-05-10 23:53:50 +00:00
foreach (var contract in contracts)
2013-04-20 00:05:48 +00:00
{
AutoRegisterImplementations(contract);
}
}
protected void AutoRegisterImplementations<TContract>()
{
AutoRegisterImplementations(typeof(TContract));
}
private void AutoRegisterImplementations(Type contractType)
{
2013-05-10 23:53:50 +00:00
if (contractType.Name.Contains("oots"))
{
int adawd = 12;
}
var implementations = GetImplementations(contractType).Where(c => !c.IsGenericTypeDefinition).ToList();
2013-04-20 00:05:48 +00:00
if (implementations.Count == 0)
{
return;
}
if (implementations.Count == 1)
{
2013-05-10 23:53:50 +00:00
var impl = implementations.Single();
if (impl.HasAttribute<SingletonAttribute>())
{
2013-05-10 23:53:50 +00:00
Container.RegisterSingleton(contractType, impl);
}
else
{
2013-05-10 23:53:50 +00:00
Container.Register(contractType, impl);
}
2013-04-20 00:05:48 +00:00
}
else
{
2013-05-10 23:53:50 +00:00
Container.RegisterAll(contractType, implementations);
2013-04-20 00:05:48 +00:00
}
}
private IEnumerable<Type> GetImplementations(Type contractType)
{
return _loadedTypes
.Where(implementation =>
contractType.IsAssignableFrom(implementation) &&
!implementation.IsInterface &&
!implementation.IsAbstract
);
}
}
}