diff --git a/frontend/src/Settings/General/GeneralSettings.js b/frontend/src/Settings/General/GeneralSettings.js
index 3870e2754..995b3fce3 100644
--- a/frontend/src/Settings/General/GeneralSettings.js
+++ b/frontend/src/Settings/General/GeneralSettings.js
@@ -24,10 +24,7 @@ const requiresRestartKeys = [
'enableSsl',
'sslPort',
'sslCertPath',
- 'sslCertPassword',
- 'authenticationMethod',
- 'username',
- 'password'
+ 'sslCertPassword'
];
class GeneralSettings extends Component {
diff --git a/frontend/src/Settings/General/SecuritySettings.js b/frontend/src/Settings/General/SecuritySettings.js
index 4469b2494..8d2039ea1 100644
--- a/frontend/src/Settings/General/SecuritySettings.js
+++ b/frontend/src/Settings/General/SecuritySettings.js
@@ -86,7 +86,6 @@ class SecuritySettings extends Component {
name="authenticationMethod"
values={authenticationMethodOptions}
helpText={translate('AuthenticationMethodHelpText')}
- helpTextWarning={translate('RestartRequiredHelpTextWarning')}
onChange={onInputChange}
{...authenticationMethod}
/>
@@ -100,7 +99,6 @@ class SecuritySettings extends Component {
@@ -115,7 +113,6 @@ class SecuritySettings extends Component {
diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs
index 0b8a6f15d..7392c3b85 100644
--- a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs
+++ b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Globalization;
using System.Linq;
using FluentAssertions;
@@ -20,8 +20,7 @@ public class SentryTargetFixture : TestBase
private static Exception[] FilteredExceptions = new Exception[]
{
- new UnauthorizedAccessException(),
- new TinyIoC.TinyIoCResolutionException(typeof(string))
+ new UnauthorizedAccessException()
};
[SetUp]
diff --git a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs
index 0d79a643d..f697d997d 100644
--- a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs
+++ b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs
@@ -1,8 +1,13 @@
-using System.Linq;
+using System.Linq;
+using DryIoc;
+using DryIoc.Microsoft.DependencyInjection;
using FluentAssertions;
+using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
+using NzbDrone.Common.Composition.Extensions;
using NzbDrone.Common.EnvironmentInfo;
-using NzbDrone.Core.Datastore;
+using NzbDrone.Common.Instrumentation.Extensions;
+using NzbDrone.Core.Datastore.Extensions;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Test.Common;
@@ -16,12 +21,16 @@ public class ServiceFactoryFixture : TestBase
[Test]
public void event_handlers_should_be_unique()
{
- var container = MainAppContainerBuilder.BuildContainer(new StartupContext());
- container.Register(new MainDatabase(null));
- container.Register(new LogDatabase(null));
- container.Resolve().Register();
+ var container = new Container(rules => rules.WithNzbDroneRules())
+ .AddNzbDroneLogger()
+ .AutoAddServices(Bootstrap.ASSEMBLIES)
+ .AddDummyDatabase()
+ .AddStartupContext(new StartupContext("first", "second"))
+ .GetServiceProvider();
- Mocker.SetConstant(container);
+ container.GetRequiredService().Register();
+
+ Mocker.SetConstant(container);
var handlers = Subject.BuildAll>()
.Select(c => c.GetType().FullName);
diff --git a/src/NzbDrone.Common/Composition/AssemblyLoader.cs b/src/NzbDrone.Common/Composition/AssemblyLoader.cs
new file mode 100644
index 000000000..4e8eee8dc
--- /dev/null
+++ b/src/NzbDrone.Common/Composition/AssemblyLoader.cs
@@ -0,0 +1,87 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Runtime.Loader;
+using NzbDrone.Common.EnvironmentInfo;
+
+namespace NzbDrone.Common.Composition
+{
+ public class AssemblyLoader
+ {
+ static AssemblyLoader()
+ {
+ AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ContainerResolveEventHandler);
+ }
+
+ public static IEnumerable Load(IEnumerable assemblyNames)
+ {
+ var toLoad = assemblyNames.ToList();
+ toLoad.Add("Radarr.Common");
+ toLoad.Add(OsInfo.IsWindows ? "Radarr.Windows" : "Radarr.Mono");
+
+ var toRegisterResolver = new List { "System.Data.SQLite" };
+ toRegisterResolver.AddRange(assemblyNames.Intersect(new[] { "Radarr.Core" }));
+ RegisterNativeResolver(toRegisterResolver);
+
+ var startupPath = AppDomain.CurrentDomain.BaseDirectory;
+
+ return toLoad.Select(x =>
+ AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(startupPath, $"{x}.dll")));
+ }
+
+ private static Assembly ContainerResolveEventHandler(object sender, ResolveEventArgs args)
+ {
+ var resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location);
+ var assemblyPath = resolver.ResolveAssemblyToPath(new AssemblyName(args.Name));
+
+ if (assemblyPath == null)
+ {
+ return null;
+ }
+
+ return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
+ }
+
+ public static void RegisterNativeResolver(IEnumerable assemblyNames)
+ {
+ foreach (var name in assemblyNames)
+ {
+ // This ensures we look for sqlite3 using libsqlite3.so.0 on Linux and not libsqlite3.so which
+ // is less likely to exist.
+ var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(
+ Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll"));
+
+ try
+ {
+ NativeLibrary.SetDllImportResolver(assembly, LoadNativeLib);
+ }
+ catch (InvalidOperationException)
+ {
+ // This can only be set once per assembly
+ // Catch required for NzbDrone.Host tests
+ }
+ }
+ }
+
+ private static IntPtr LoadNativeLib(string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath)
+ {
+ var mappedName = libraryName;
+ if (OsInfo.IsLinux)
+ {
+ if (libraryName == "sqlite3")
+ {
+ mappedName = "libsqlite3.so.0";
+ }
+ else if (libraryName == "mediainfo")
+ {
+ mappedName = "libmediainfo.so.0";
+ }
+ }
+
+ return NativeLibrary.Load(mappedName, assembly, dllImportSearchPath);
+ }
+ }
+}
diff --git a/src/NzbDrone.Common/Composition/Container.cs b/src/NzbDrone.Common/Composition/Container.cs
deleted file mode 100644
index d65d7d19b..000000000
--- a/src/NzbDrone.Common/Composition/Container.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using TinyIoC;
-
-namespace NzbDrone.Common.Composition
-{
- public class Container : IContainer
- {
- private readonly TinyIoCContainer _container;
- private readonly List _loadedTypes;
-
- public Container(TinyIoCContainer container, List loadedTypes)
- {
- _container = container;
- _loadedTypes = loadedTypes;
- _container.Register(this);
- }
-
- public void Register()
- where TImplementation : class, TService
- where TService : class
- {
- _container.Register();
- }
-
- public void Register(T instance)
- where T : class
- {
- _container.Register(instance);
- }
-
- public T Resolve()
- where T : class
- {
- return _container.Resolve();
- }
-
- public object Resolve(Type type)
- {
- return _container.Resolve(type);
- }
-
- public void Register(Type serviceType, Type implementationType)
- {
- _container.Register(serviceType, implementationType);
- }
-
- public void Register(Func factory)
- where TService : class
- {
- _container.Register((c, n) => factory(this));
- }
-
- public void RegisterSingleton(Type service, Type implementation)
- {
- var factory = CreateSingletonImplementationFactory(implementation);
-
- _container.Register(service, factory);
- _container.Register(service, factory, implementation.FullName);
- }
-
- public IEnumerable ResolveAll()
- where T : class
- {
- return _container.ResolveAll();
- }
-
- public void RegisterAllAsSingleton(Type service, IEnumerable implementationList)
- {
- foreach (var implementation in implementationList)
- {
- var factory = CreateSingletonImplementationFactory(implementation);
-
- _container.Register(service, factory, implementation.FullName);
- }
- }
-
- private Func CreateSingletonImplementationFactory(Type implementation)
- {
- const string singleImplPrefix = "singleImpl_";
-
- _container.Register(implementation, implementation, singleImplPrefix + implementation.FullName).AsSingleton();
-
- return (c, p) => _container.Resolve(implementation, singleImplPrefix + implementation.FullName);
- }
-
- public bool IsTypeRegistered(Type type)
- {
- return _container.CanResolve(type);
- }
-
- public IEnumerable GetImplementations(Type contractType)
- {
- return _loadedTypes
- .Where(implementation =>
- contractType.IsAssignableFrom(implementation) &&
- !implementation.IsInterface &&
- !implementation.IsAbstract);
- }
- }
-}
diff --git a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs
deleted file mode 100644
index 4439b3bde..000000000
--- a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Loader;
-using NzbDrone.Common.EnvironmentInfo;
-using NzbDrone.Common.Messaging;
-using TinyIoC;
-
-namespace NzbDrone.Common.Composition
-{
- public abstract class ContainerBuilderBase
- {
- private readonly List _loadedTypes;
-
- protected IContainer Container { get; }
-
- protected ContainerBuilderBase(IStartupContext args, List assemblies)
- {
- _loadedTypes = new List();
-
- assemblies.Add(OsInfo.IsWindows ? "Radarr.Windows" : "Radarr.Mono");
- assemblies.Add("Radarr.Common");
-
- var startupPath = AppDomain.CurrentDomain.BaseDirectory;
-
- foreach (var assemblyName in assemblies)
- {
- _loadedTypes.AddRange(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(startupPath, $"{assemblyName}.dll")).GetExportedTypes());
- }
-
- var toRegisterResolver = new List { "System.Data.SQLite" };
- toRegisterResolver.AddRange(assemblies.Intersect(new[] { "Radarr.Core" }));
- RegisterNativeResolver(toRegisterResolver);
- AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ContainerResolveEventHandler);
-
- Container = new Container(new TinyIoCContainer(), _loadedTypes);
- AutoRegisterInterfaces();
- Container.Register(args);
- }
-
- private static Assembly ContainerResolveEventHandler(object sender, ResolveEventArgs args)
- {
- var resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location);
- var assemblyPath = resolver.ResolveAssemblyToPath(new AssemblyName(args.Name));
-
- if (assemblyPath == null)
- {
- return null;
- }
-
- return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
- }
-
- public static void RegisterNativeResolver(IEnumerable assemblyNames)
- {
- // This ensures we look for sqlite3 using libsqlite3.so.0 on Linux and not libsqlite3.so which
- // is less likely to exist.
- foreach (var name in assemblyNames)
- {
- var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(
- Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll"));
-
- try
- {
- NativeLibrary.SetDllImportResolver(assembly, LoadNativeLib);
- }
- catch (InvalidOperationException)
- {
- // This can only be set once per assembly
- // Catch required for NzbDrone.Host tests
- }
- }
- }
-
- private static IntPtr LoadNativeLib(string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath)
- {
- var mappedName = libraryName;
- if (OsInfo.IsLinux)
- {
- if (libraryName == "sqlite3")
- {
- mappedName = "libsqlite3.so.0";
- }
- else if (libraryName == "mediainfo")
- {
- mappedName = "libmediainfo.so.0";
- }
- }
-
- return NativeLibrary.Load(mappedName, assembly, dllImportSearchPath);
- }
-
- private void AutoRegisterInterfaces()
- {
- var loadedInterfaces = _loadedTypes.Where(t => t.IsInterface).ToList();
- var implementedInterfaces = _loadedTypes.SelectMany(t => t.GetInterfaces());
-
- var contracts = loadedInterfaces.Union(implementedInterfaces).Where(c => !c.IsGenericTypeDefinition && !string.IsNullOrWhiteSpace(c.FullName))
- .Where(c => !c.FullName.StartsWith("System"))
- .Except(new List { typeof(IMessage), typeof(IEvent), typeof(IContainer) }).Distinct().OrderBy(c => c.FullName);
-
- foreach (var contract in contracts)
- {
- AutoRegisterImplementations(contract);
- }
- }
-
- protected void AutoRegisterImplementations()
- {
- AutoRegisterImplementations(typeof(TContract));
- }
-
- private void AutoRegisterImplementations(Type contractType)
- {
- var implementations = Container.GetImplementations(contractType).Where(c => !c.IsGenericTypeDefinition).ToList();
-
- if (implementations.Count == 0)
- {
- return;
- }
-
- if (implementations.Count == 1)
- {
- var impl = implementations.Single();
- Container.RegisterSingleton(contractType, impl);
- }
- else
- {
- Container.RegisterAllAsSingleton(contractType, implementations);
- }
- }
- }
-}
diff --git a/src/NzbDrone.Common/Composition/Extensions.cs b/src/NzbDrone.Common/Composition/Extensions.cs
new file mode 100644
index 000000000..d3cc6b52c
--- /dev/null
+++ b/src/NzbDrone.Common/Composition/Extensions.cs
@@ -0,0 +1,37 @@
+using System.Collections.Generic;
+using System.Linq;
+using DryIoc;
+using NzbDrone.Common.EnvironmentInfo;
+
+namespace NzbDrone.Common.Composition.Extensions
+{
+ public static class ServiceCollectionExtensions
+ {
+ public static Rules WithNzbDroneRules(this Rules rules)
+ {
+ return rules.WithMicrosoftDependencyInjectionRules()
+ .WithAutoConcreteTypeResolution()
+ .WithDefaultReuse(Reuse.Singleton);
+ }
+
+ public static IContainer AddStartupContext(this IContainer container, StartupContext context)
+ {
+ container.RegisterInstance(context, ifAlreadyRegistered: IfAlreadyRegistered.Replace);
+ return container;
+ }
+
+ public static IContainer AutoAddServices(this IContainer container, List assemblyNames)
+ {
+ var assemblies = AssemblyLoader.Load(assemblyNames);
+
+ container.RegisterMany(assemblies,
+ serviceTypeCondition: type => type.IsInterface && !string.IsNullOrWhiteSpace(type.FullName) && !type.FullName.StartsWith("System"),
+ reuse: Reuse.Singleton);
+
+ var knownTypes = new KnownTypes(assemblies.SelectMany(x => x.GetTypes()).ToList());
+ container.RegisterInstance(knownTypes);
+
+ return container;
+ }
+ }
+}
diff --git a/src/NzbDrone.Common/Composition/IContainer.cs b/src/NzbDrone.Common/Composition/IContainer.cs
deleted file mode 100644
index 9e7402017..000000000
--- a/src/NzbDrone.Common/Composition/IContainer.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace NzbDrone.Common.Composition
-{
- public interface IContainer
- {
- void Register(T instance)
- where T : class;
-
- void Register()
- where TImplementation : class, TService
- where TService : class;
- T Resolve()
- where T : class;
- object Resolve(Type type);
- void Register(Type serviceType, Type implementationType);
- void Register(Func factory)
- where TService : class;
- void RegisterSingleton(Type service, Type implementation);
- IEnumerable ResolveAll()
- where T : class;
- void RegisterAllAsSingleton(Type registrationType, IEnumerable implementationList);
- bool IsTypeRegistered(Type type);
-
- IEnumerable GetImplementations(Type contractType);
- }
-}
diff --git a/src/NzbDrone.Common/Composition/KnownTypes.cs b/src/NzbDrone.Common/Composition/KnownTypes.cs
new file mode 100644
index 000000000..3f816633f
--- /dev/null
+++ b/src/NzbDrone.Common/Composition/KnownTypes.cs
@@ -0,0 +1,31 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace NzbDrone.Common.Composition
+{
+ public class KnownTypes
+ {
+ private List _knownTypes;
+
+ // So unity can resolve for tests
+ public KnownTypes()
+ : this(new List())
+ {
+ }
+
+ public KnownTypes(List loadedTypes)
+ {
+ _knownTypes = loadedTypes;
+ }
+
+ public IEnumerable GetImplementations(Type contractType)
+ {
+ return _knownTypes
+ .Where(implementation =>
+ contractType.IsAssignableFrom(implementation) &&
+ !implementation.IsInterface &&
+ !implementation.IsAbstract);
+ }
+ }
+}
diff --git a/src/NzbDrone.Common/Instrumentation/Extensions/CompositionExtensions.cs b/src/NzbDrone.Common/Instrumentation/Extensions/CompositionExtensions.cs
new file mode 100644
index 000000000..10b7d4af4
--- /dev/null
+++ b/src/NzbDrone.Common/Instrumentation/Extensions/CompositionExtensions.cs
@@ -0,0 +1,14 @@
+using DryIoc;
+using NLog;
+
+namespace NzbDrone.Common.Instrumentation.Extensions
+{
+ public static class CompositionExtensions
+ {
+ public static IContainer AddNzbDroneLogger(this IContainer container)
+ {
+ container.Register(Made.Of(() => LogManager.GetLogger(Arg.Index(0)), r => r.Parent.ImplementationType.Name.ToString()), reuse: Reuse.Transient);
+ return container;
+ }
+ }
+}
diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
index 1067e319f..13da47865 100644
--- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
+++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
@@ -42,10 +42,7 @@ public class SentryTarget : TargetWithLayout
"UnauthorizedAccessException",
// Filter out people stuck in boot loops
- "CorruptDatabaseException",
-
- // This also filters some people in boot loops
- "TinyIoCResolutionException"
+ "CorruptDatabaseException"
};
public static readonly List FilteredExceptionMessages = new List
diff --git a/src/NzbDrone.Common/Radarr.Common.csproj b/src/NzbDrone.Common/Radarr.Common.csproj
index 6a1bdac09..499df6da5 100644
--- a/src/NzbDrone.Common/Radarr.Common.csproj
+++ b/src/NzbDrone.Common/Radarr.Common.csproj
@@ -4,9 +4,12 @@
ISMUSL
+
+
-
+
+
diff --git a/src/NzbDrone.Common/ServiceFactory.cs b/src/NzbDrone.Common/ServiceFactory.cs
index 4f7e4bb0b..06b3749e8 100644
--- a/src/NzbDrone.Common/ServiceFactory.cs
+++ b/src/NzbDrone.Common/ServiceFactory.cs
@@ -1,7 +1,7 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
-using NzbDrone.Common.Composition;
+using Microsoft.Extensions.DependencyInjection;
namespace NzbDrone.Common
{
@@ -17,9 +17,9 @@ IEnumerable BuildAll()
public class ServiceFactory : IServiceFactory
{
- private readonly IContainer _container;
+ private readonly System.IServiceProvider _container;
- public ServiceFactory(IContainer container)
+ public ServiceFactory(System.IServiceProvider container)
{
_container = container;
}
@@ -27,23 +27,23 @@ public ServiceFactory(IContainer container)
public T Build()
where T : class
{
- return _container.Resolve();
+ return _container.GetRequiredService();
}
public IEnumerable BuildAll()
where T : class
{
- return _container.ResolveAll().GroupBy(c => c.GetType().FullName).Select(g => g.First());
+ return _container.GetServices().GroupBy(c => c.GetType().FullName).Select(g => g.First());
}
public object Build(Type contract)
{
- return _container.Resolve(contract);
+ return _container.GetRequiredService(contract);
}
public IEnumerable GetImplementations(Type contract)
{
- return _container.GetImplementations(contract);
+ return _container.GetServices(contract).Select(x => x.GetType());
}
}
}
diff --git a/src/NzbDrone.Common/TinyIoC.cs b/src/NzbDrone.Common/TinyIoC.cs
deleted file mode 100644
index a9750319d..000000000
--- a/src/NzbDrone.Common/TinyIoC.cs
+++ /dev/null
@@ -1,3791 +0,0 @@
-//===============================================================================
-// TinyIoC
-//
-// An easy to use, hassle free, Inversion of Control Container for small projects
-// and beginners alike.
-//
-// https://github.com/grumpydev/TinyIoC
-//===============================================================================
-// Copyright © Steven Robbins. All rights reserved.
-// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
-// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
-// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-// FITNESS FOR A PARTICULAR PURPOSE.
-//===============================================================================
-
-#pragma warning disable SX1101, SA1108, SA1119, SA1124, SA1200, SA1208, SA1314, SA1403, SA1503, SA1514, SA1515, SA1519, SX1309
-
-#region Preprocessor Directives
-
-// Uncomment this line if you want the container to automatically
-// register the TinyMessenger messenger/event aggregator
-//#define TINYMESSENGER
-
-// Preprocessor directives for enabling/disabling functionality
-// depending on platform features. If the platform has an appropriate
-// #DEFINE then these should be set automatically below.
-#define EXPRESSIONS // Platform supports System.Linq.Expressions
-#define COMPILED_EXPRESSIONS // Platform supports compiling expressions
-#define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object
-#define UNBOUND_GENERICS_GETCONSTRUCTORS // Platform supports GetConstructors on unbound generic types
-#define GETPARAMETERS_OPEN_GENERICS // Platform supports GetParameters on open generics
-#define RESOLVE_OPEN_GENERICS // Platform supports resolving open generics
-#define READER_WRITER_LOCK_SLIM // Platform supports ReaderWriterLockSlim
-
-//// NETFX_CORE
-//#if NETFX_CORE
-//#endif
-
-// CompactFramework / Windows Phone 7
-// By default does not support System.Linq.Expressions.
-// AppDomain object does not support enumerating all assemblies in the app domain.
-#if PocketPC || WINDOWS_PHONE
-#undef EXPRESSIONS
-#undef COMPILED_EXPRESSIONS
-#undef APPDOMAIN_GETASSEMBLIES
-#undef UNBOUND_GENERICS_GETCONSTRUCTORS
-#endif
-
-// PocketPC has a bizarre limitation on enumerating parameters on unbound generic methods.
-// We need to use a slower workaround in that case.
-#if PocketPC
-#undef GETPARAMETERS_OPEN_GENERICS
-#undef RESOLVE_OPEN_GENERICS
-#undef READER_WRITER_LOCK_SLIM
-#endif
-
-#if SILVERLIGHT
-#undef APPDOMAIN_GETASSEMBLIES
-#endif
-
-#if NETFX_CORE
-#undef APPDOMAIN_GETASSEMBLIES
-#undef RESOLVE_OPEN_GENERICS
-#endif
-
-#if COMPILED_EXPRESSIONS
-#define USE_OBJECT_CONSTRUCTOR
-#endif
-
-#endregion
-namespace TinyIoC
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
-
-#if EXPRESSIONS
- using System.Linq.Expressions;
- using NLog;
- using System.Threading;
-
-#endif
-
-#if NETFX_CORE
- using System.Threading.Tasks;
- using Windows.Storage.Search;
- using Windows.Storage;
- using Windows.UI.Xaml.Shapes;
-#endif
-
- #region SafeDictionary
-#if READER_WRITER_LOCK_SLIM
- public class SafeDictionary : IDisposable
- {
- private readonly ReaderWriterLockSlim _padlock = new ReaderWriterLockSlim();
- private readonly Dictionary _Dictionary = new Dictionary();
-
- public TValue this[TKey key]
- {
- set
- {
- _padlock.EnterWriteLock();
-
- try
- {
- TValue current;
- if (_Dictionary.TryGetValue(key, out current))
- {
- var disposable = current as IDisposable;
-
- if (disposable != null)
- disposable.Dispose();
- }
-
- _Dictionary[key] = value;
- }
- finally
- {
- _padlock.ExitWriteLock();
- }
- }
- }
-
- public bool TryGetValue(TKey key, out TValue value)
- {
- _padlock.EnterReadLock();
- try
- {
- return _Dictionary.TryGetValue(key, out value);
- }
- finally
- {
- _padlock.ExitReadLock();
- }
- }
-
- public bool Remove(TKey key)
- {
- _padlock.EnterWriteLock();
- try
- {
- return _Dictionary.Remove(key);
- }
- finally
- {
- _padlock.ExitWriteLock();
- }
- }
-
- public void Clear()
- {
- _padlock.EnterWriteLock();
- try
- {
- _Dictionary.Clear();
- }
- finally
- {
- _padlock.ExitWriteLock();
- }
- }
-
- public IEnumerable Keys
- {
- get
- {
- _padlock.EnterReadLock();
- try
- {
- return new List(_Dictionary.Keys);
- }
- finally
- {
- _padlock.ExitReadLock();
- }
- }
- }
-
- #region IDisposable Members
-
- public void Dispose()
- {
- _padlock.EnterWriteLock();
-
- try
- {
- var disposableItems = from item in _Dictionary.Values
- where item is IDisposable
- select item as IDisposable;
-
- foreach (var item in disposableItems)
- {
- item.Dispose();
- }
- }
- finally
- {
- _padlock.ExitWriteLock();
- }
-
- GC.SuppressFinalize(this);
- }
-
- #endregion
- }
-#else
- public class SafeDictionary : IDisposable
- {
- private readonly object _Padlock = new object();
- private readonly Dictionary _Dictionary = new Dictionary();
-
- public TValue this[TKey key]
- {
- set
- {
- lock (_Padlock)
- {
- TValue current;
- if (_Dictionary.TryGetValue(key, out current))
- {
- var disposable = current as IDisposable;
-
- if (disposable != null)
- disposable.Dispose();
- }
-
- _Dictionary[key] = value;
- }
- }
- }
-
- public bool TryGetValue(TKey key, out TValue value)
- {
- lock (_Padlock)
- {
- return _Dictionary.TryGetValue(key, out value);
- }
- }
-
- public bool Remove(TKey key)
- {
- lock (_Padlock)
- {
- return _Dictionary.Remove(key);
- }
- }
-
- public void Clear()
- {
- lock (_Padlock)
- {
- _Dictionary.Clear();
- }
- }
-
- public IEnumerable Keys
- {
- get
- {
- return _Dictionary.Keys;
- }
- }
- #region IDisposable Members
-
- public void Dispose()
- {
- lock (_Padlock)
- {
- var disposableItems = from item in _Dictionary.Values
- where item is IDisposable
- select item as IDisposable;
-
- foreach (var item in disposableItems)
- {
- item.Dispose();
- }
- }
-
- GC.SuppressFinalize(this);
- }
-
- #endregion
- }
-#endif
- #endregion
-
- #region Extensions
- public static class AssemblyExtensions
- {
- public static Type[] SafeGetTypes(this Assembly assembly)
- {
- Type[] assemblies;
-
- try
- {
- assemblies = assembly.GetTypes();
- }
- catch (System.IO.FileNotFoundException)
- {
- assemblies = Array.Empty();
- }
- catch (NotSupportedException)
- {
- assemblies = Array.Empty();
- }
-#if !NETFX_CORE
- catch (ReflectionTypeLoadException e)
- {
- assemblies = e.Types.Where(t => t != null).ToArray();
- }
-#endif
- return assemblies;
- }
- }
-
- public static class TypeExtensions
- {
- private static SafeDictionary _genericMethodCache;
-
- static TypeExtensions()
- {
- _genericMethodCache = new SafeDictionary();
- }
-
- //#if NETFX_CORE
- // ///
- // /// Gets a generic method from a type given the method name, generic types and parameter types
- // ///
- // /// Source type
- // /// Name of the method
- // /// Generic types to use to make the method generic
- // /// Method parameters
- // /// MethodInfo or null if no matches found
- // ///
- // ///
- // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)
- // {
- // MethodInfo method;
- // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);
-
- // // Shouldn't need any additional locking
- // // we don't care if we do the method info generation
- // // more than once before it gets cached.
- // if (!_genericMethodCache.TryGetValue(cacheKey, out method))
- // {
- // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes);
- // _genericMethodCache[cacheKey] = method;
- // }
-
- // return method;
- // }
- //#else
- ///
- /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types
- ///
- /// Source type
- /// Binding flags
- /// Name of the method
- /// Generic types to use to make the method generic
- /// Method parameters
- /// MethodInfo or null if no matches found
- ///
- ///
- public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
- {
- MethodInfo method;
- var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);
-
- // Shouldn't need any additional locking
- // we don't care if we do the method info generation
- // more than once before it gets cached.
- if (!_genericMethodCache.TryGetValue(cacheKey, out method))
- {
- method = GetMethod(sourceType, bindingFlags, methodName, genericTypes, parameterTypes);
- _genericMethodCache[cacheKey] = method;
- }
-
- return method;
- }
-
- //#endif
-#if NETFX_CORE
- private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes)
- {
- var methods =
- sourceType.GetMethods(flags).Where(
- mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(
- mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).
- Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(
- mi => mi.MakeGenericMethod(genericTypes)).Where(
- mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();
-
- if (methods.Count > 1)
- {
- throw new AmbiguousMatchException();
- }
-
- return methods.FirstOrDefault();
- }
-#else
- private static MethodInfo GetMethod(Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)
- {
-#if GETPARAMETERS_OPEN_GENERICS
- var methods =
- sourceType.GetMethods(bindingFlags).Where(
- mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(
- mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).
- Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(
- mi => mi.MakeGenericMethod(genericTypes)).Where(
- mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();
-#else
- var validMethods = from method in sourceType.GetMethods(bindingFlags)
- where method.Name == methodName
- where method.IsGenericMethod
- where method.GetGenericArguments().Length == genericTypes.Length
- let genericMethod = method.MakeGenericMethod(genericTypes)
- where genericMethod.GetParameters().Count() == parameterTypes.Length
- where genericMethod.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)
- select genericMethod;
-
- var methods = validMethods.ToList();
-#endif
- if (methods.Count > 1)
- {
- throw new AmbiguousMatchException();
- }
-
- return methods.FirstOrDefault();
- }
-#endif
-
- private sealed class GenericMethodCacheKey
- {
- private readonly Type _sourceType;
-
- private readonly string _methodName;
-
- private readonly Type[] _genericTypes;
-
- private readonly Type[] _parameterTypes;
-
- private readonly int _hashCode;
-
- public GenericMethodCacheKey(Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)
- {
- _sourceType = sourceType;
- _methodName = methodName;
- _genericTypes = genericTypes;
- _parameterTypes = parameterTypes;
- _hashCode = GenerateHashCode();
- }
-
- public override bool Equals(object obj)
- {
- var cacheKey = obj as GenericMethodCacheKey;
- if (cacheKey == null)
- return false;
-
- if (_sourceType != cacheKey._sourceType)
- return false;
-
- if (!string.Equals(_methodName, cacheKey._methodName, StringComparison.Ordinal))
- return false;
-
- if (_genericTypes.Length != cacheKey._genericTypes.Length)
- return false;
-
- if (_parameterTypes.Length != cacheKey._parameterTypes.Length)
- return false;
-
- for (int i = 0; i < _genericTypes.Length; ++i)
- {
- if (_genericTypes[i] != cacheKey._genericTypes[i])
- return false;
- }
-
- for (int i = 0; i < _parameterTypes.Length; ++i)
- {
- if (_parameterTypes[i] != cacheKey._parameterTypes[i])
- return false;
- }
-
- return true;
- }
-
- public override int GetHashCode()
- {
- return _hashCode;
- }
-
- private int GenerateHashCode()
- {
- unchecked
- {
- var result = _sourceType.GetHashCode();
-
- result = (result * 397) ^ _methodName.GetHashCode();
-
- for (int i = 0; i < _genericTypes.Length; ++i)
- {
- result = (result * 397) ^ _genericTypes[i].GetHashCode();
- }
-
- for (int i = 0; i < _parameterTypes.Length; ++i)
- {
- result = (result * 397) ^ _parameterTypes[i].GetHashCode();
- }
-
- return result;
- }
- }
- }
- }
-
- // @mbrit - 2012-05-22 - shim for ForEach call on List...
-#if NETFX_CORE
- internal static class ListExtender
- {
- internal static void ForEach(this List list, Action callback)
- {
- foreach (T obj in list)
- callback(obj);
- }
- }
-#endif
-
- #endregion
-
- #region TinyIoC Exception Types
- public class TinyIoCResolutionException : Exception
- {
- private const string ERROR_TEXT = "Unable to resolve type: {0}";
-
- public TinyIoCResolutionException(Type type)
- : base(string.Format(ERROR_TEXT, type.FullName))
- {
- }
-
- public TinyIoCResolutionException(Type type, Exception innerException)
- : base(string.Format(ERROR_TEXT, type.FullName), innerException)
- {
- }
- }
-
- public class TinyIoCRegistrationTypeException : Exception
- {
- private const string REGISTER_ERROR_TEXT = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}.";
-
- public TinyIoCRegistrationTypeException(Type type, string factory)
- : base(string.Format(REGISTER_ERROR_TEXT, type.FullName, factory))
- {
- }
-
- public TinyIoCRegistrationTypeException(Type type, string factory, Exception innerException)
- : base(string.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException)
- {
- }
- }
-
- public class TinyIoCRegistrationException : Exception
- {
- private const string CONVERT_ERROR_TEXT = "Cannot convert current registration of {0} to {1}";
- private const string GENERIC_CONSTRAINT_ERROR_TEXT = "Type {1} is not valid for a registration of type {0}";
-
- public TinyIoCRegistrationException(Type type, string method)
- : base(string.Format(CONVERT_ERROR_TEXT, type.FullName, method))
- {
- }
-
- public TinyIoCRegistrationException(Type type, string method, Exception innerException)
- : base(string.Format(CONVERT_ERROR_TEXT, type.FullName, method), innerException)
- {
- }
-
- public TinyIoCRegistrationException(Type registerType, Type implementationType)
- : base(string.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName))
- {
- }
-
- public TinyIoCRegistrationException(Type registerType, Type implementationType, Exception innerException)
- : base(string.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException)
- {
- }
- }
-
- public class TinyIoCWeakReferenceException : Exception
- {
- private const string ERROR_TEXT = "Unable to instantiate {0} - referenced object has been reclaimed";
-
- public TinyIoCWeakReferenceException(Type type)
- : base(string.Format(ERROR_TEXT, type.FullName))
- {
- }
-
- public TinyIoCWeakReferenceException(Type type, Exception innerException)
- : base(string.Format(ERROR_TEXT, type.FullName), innerException)
- {
- }
- }
-
- public class TinyIoCConstructorResolutionException : Exception
- {
- private const string ERROR_TEXT = "Unable to resolve constructor for {0} using provided Expression.";
-
- public TinyIoCConstructorResolutionException(Type type)
- : base(string.Format(ERROR_TEXT, type.FullName))
- {
- }
-
- public TinyIoCConstructorResolutionException(Type type, Exception innerException)
- : base(string.Format(ERROR_TEXT, type.FullName), innerException)
- {
- }
-
- public TinyIoCConstructorResolutionException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
-
- public TinyIoCConstructorResolutionException(string message)
- : base(message)
- {
- }
- }
-
- public class TinyIoCAutoRegistrationException : Exception
- {
- private const string ERROR_TEXT = "Duplicate implementation of type {0} found ({1}).";
-
- public TinyIoCAutoRegistrationException(Type registerType, IEnumerable types)
- : base(string.Format(ERROR_TEXT, registerType, GetTypesString(types)))
- {
- }
-
- public TinyIoCAutoRegistrationException(Type registerType, IEnumerable types, Exception innerException)
- : base(string.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException)
- {
- }
-
- private static string GetTypesString(IEnumerable types)
- {
- var typeNames = from type in types
- select type.FullName;
-
- return string.Join(",", typeNames.ToArray());
- }
- }
- #endregion
-
- #region Public Setup / Settings Classes
- ///
- /// Name/Value pairs for specifying "user" parameters when resolving
- ///
- public sealed class NamedParameterOverloads : Dictionary
- {
- public static NamedParameterOverloads FromIDictionary(IDictionary data)
- {
- return data as NamedParameterOverloads ?? new NamedParameterOverloads(data);
- }
-
- public NamedParameterOverloads()
- {
- }
-
- public NamedParameterOverloads(IDictionary data)
- : base(data)
- {
- }
-
- private static readonly NamedParameterOverloads _Default = new NamedParameterOverloads();
-
- public static NamedParameterOverloads Default => _Default;
- }
-
- public enum UnregisteredResolutionActions
- {
- ///
- /// Attempt to resolve type, even if the type isn't registered.
- ///
- /// Registered types/options will always take precedence.
- ///
- AttemptResolve,
-
- ///
- /// Fail resolution if type not explicitly registered
- ///
- Fail,
-
- ///
- /// Attempt to resolve unregistered type if requested type is generic
- /// and no registration exists for the specific generic parameters used.
- ///
- /// Registered types/options will always take precedence.
- ///
- GenericsOnly
- }
-
- public enum NamedResolutionFailureActions
- {
- AttemptUnnamedResolution,
- Fail
- }
-
- public enum DuplicateImplementationActions
- {
- RegisterSingle,
- RegisterMultiple,
- Fail
- }
-
- ///
- /// Resolution settings
- ///
- public sealed class ResolveOptions
- {
- private static readonly ResolveOptions _Default = new ResolveOptions();
- private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
- private static readonly ResolveOptions _FailUnregisteredOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.AttemptUnnamedResolution, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };
- private static readonly ResolveOptions _FailNameNotFoundOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve };
-
- private UnregisteredResolutionActions _UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve;
- public UnregisteredResolutionActions UnregisteredResolutionAction
- {
- get { return _UnregisteredResolutionAction; }
- set { _UnregisteredResolutionAction = value; }
- }
-
- private NamedResolutionFailureActions _NamedResolutionFailureAction = NamedResolutionFailureActions.Fail;
- public NamedResolutionFailureActions NamedResolutionFailureAction
- {
- get { return _NamedResolutionFailureAction; }
- set { _NamedResolutionFailureAction = value; }
- }
-
- ///
- /// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found)
- ///
- public static ResolveOptions Default => _Default;
-
- ///
- /// Preconfigured option for attempting resolution of unregistered types and failing on named resolution if name not found
- ///
- public static ResolveOptions FailNameNotFoundOnly => _FailNameNotFoundOnly;
-
- ///
- /// Preconfigured option for failing on resolving unregistered types and on named resolution if name not found
- ///
- public static ResolveOptions FailUnregisteredAndNameNotFound => _FailUnregisteredAndNameNotFound;
-
- ///
- /// Preconfigured option for failing on resolving unregistered types, but attempting unnamed resolution if name not found
- ///
- public static ResolveOptions FailUnregisteredOnly => _FailUnregisteredOnly;
- }
- #endregion
-
- public sealed partial class TinyIoCContainer : IDisposable
- {
- #region Fake NETFX_CORE Classes
-#if NETFX_CORE
- private sealed class MethodAccessException : Exception
- {
- }
-
- private sealed class AppDomain
- {
- public static AppDomain CurrentDomain { get; private set; }
-
- static AppDomain()
- {
- CurrentDomain = new AppDomain();
- }
-
- // @mbrit - 2012-05-30 - in WinRT, this should be done async...
- public async Task> GetAssembliesAsync()
- {
- var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
-
- List assemblies = new List();
-
- var files = await folder.GetFilesAsync();
-
- foreach (StorageFile file in files)
- {
- if (file.FileType == ".dll" || file.FileType == ".exe")
- {
- AssemblyName name = new AssemblyName() { Name = System.IO.Path.GetFileNameWithoutExtension(file.Name) };
- try
- {
- var asm = Assembly.Load(name);
- assemblies.Add(asm);
- }
- catch
- {
- // ignore exceptions here...
- }
- }
- }
-
- return assemblies;
- }
- }
-#endif
- #endregion
-
- #region "Fluent" API
- ///
- /// Registration options for "fluent" API
- ///
- public sealed class RegisterOptions
- {
- private TinyIoCContainer _Container;
- private TypeRegistration _Registration;
-
- public RegisterOptions(TinyIoCContainer container, TypeRegistration registration)
- {
- _Container = container;
- _Registration = registration;
- }
-
- ///
- /// Make registration a singleton (single instance) if possible
- ///
- /// RegisterOptions
- ///
- public RegisterOptions AsSingleton()
- {
- var currentFactory = _Container.GetCurrentFactory(_Registration);
-
- if (currentFactory == null)
- throw new TinyIoCRegistrationException(_Registration.Type, "singleton");
-
- return _Container.AddUpdateRegistration(_Registration, currentFactory.SingletonVariant);
- }
-
- ///
- /// Make registration multi-instance if possible
- ///
- /// RegisterOptions
- ///
- public RegisterOptions AsMultiInstance()
- {
- var currentFactory = _Container.GetCurrentFactory(_Registration);
-
- if (currentFactory == null)
- throw new TinyIoCRegistrationException(_Registration.Type, "multi-instance");
-
- return _Container.AddUpdateRegistration(_Registration, currentFactory.MultiInstanceVariant);
- }
-
- ///
- /// Make registration hold a weak reference if possible
- ///
- /// RegisterOptions
- ///
- public RegisterOptions WithWeakReference()
- {
- var currentFactory = _Container.GetCurrentFactory(_Registration);
-
- if (currentFactory == null)
- throw new TinyIoCRegistrationException(_Registration.Type, "weak reference");
-
- return _Container.AddUpdateRegistration(_Registration, currentFactory.WeakReferenceVariant);
- }
-
- ///
- /// Make registration hold a strong reference if possible
- ///
- /// RegisterOptions
- ///
- public RegisterOptions WithStrongReference()
- {
- var currentFactory = _Container.GetCurrentFactory(_Registration);
-
- if (currentFactory == null)
- throw new TinyIoCRegistrationException(_Registration.Type, "strong reference");
-
- return _Container.AddUpdateRegistration(_Registration, currentFactory.StrongReferenceVariant);
- }
-
-#if EXPRESSIONS
- public RegisterOptions UsingConstructor(Expression> constructor)
- {
- var lambda = constructor as LambdaExpression;
- if (lambda == null)
- throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
-
- var newExpression = lambda.Body as NewExpression;
- if (newExpression == null)
- throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
-
- var constructorInfo = newExpression.Constructor;
- if (constructorInfo == null)
- throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
-
- var currentFactory = _Container.GetCurrentFactory(_Registration);
- if (currentFactory == null)
- throw new TinyIoCConstructorResolutionException(typeof(RegisterType));
-
- currentFactory.SetConstructor(constructorInfo);
-
- return this;
- }
-#endif
- ///
- /// Switches to a custom lifetime manager factory if possible.
- ///
- /// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one.
- ///
- /// RegisterOptions instance
- /// Custom lifetime manager
- /// Error string to display if switch fails
- /// RegisterOptions
- public static RegisterOptions ToCustomLifetimeManager(RegisterOptions instance, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)
- {
- if (instance == null)
- throw new ArgumentNullException("instance", "instance is null.");
-
- if (lifetimeProvider == null)
- throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null.");
-
- if (string.IsNullOrEmpty(errorString))
- throw new ArgumentException("errorString is null or empty.", "errorString");
-
- var currentFactory = instance._Container.GetCurrentFactory(instance._Registration);
-
- if (currentFactory == null)
- throw new TinyIoCRegistrationException(instance._Registration.Type, errorString);
-
- return instance._Container.AddUpdateRegistration(instance._Registration, currentFactory.GetCustomObjectLifetimeVariant(lifetimeProvider, errorString));
- }
- }
-
- ///
- /// Registration options for "fluent" API when registering multiple implementations
- ///
- public sealed class MultiRegisterOptions
- {
- private IEnumerable _RegisterOptions;
-
- ///
- /// Initializes a new instance of the MultiRegisterOptions class.
- ///
- /// Registration options
- public MultiRegisterOptions(IEnumerable registerOptions)
- {
- _RegisterOptions = registerOptions;
- }
-
- ///
- /// Make registration a singleton (single instance) if possible
- ///
- /// RegisterOptions
- ///
- public MultiRegisterOptions AsSingleton()
- {
- _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton());
- return this;
- }
-
- ///
- /// Make registration multi-instance if possible
- ///
- /// MultiRegisterOptions
- ///
- public MultiRegisterOptions AsMultiInstance()
- {
- _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance());
- return this;
- }
-
- private IEnumerable ExecuteOnAllRegisterOptions(Func action)
- {
- var newRegisterOptions = new List();
-
- foreach (var registerOption in _RegisterOptions)
- {
- newRegisterOptions.Add(action(registerOption));
- }
-
- return newRegisterOptions;
- }
- }
- #endregion
-
- #region Public API
- #region Child Containers
- public TinyIoCContainer GetChildContainer()
- {
- return new TinyIoCContainer(this);
- }
- #endregion
-
- #region Registration
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
- ///
- /// If more than one class implements an interface then only one implementation will be registered
- /// although no error will be thrown.
- ///
- public void AutoRegister()
- {
-#if APPDOMAIN_GETASSEMBLIES
- AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, null);
-#else
- AutoRegisterInternal(new Assembly[] {this.GetType().Assembly()}, true, null);
-#endif
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
- /// Types will only be registered if they pass the supplied registration predicate.
- ///
- /// If more than one class implements an interface then only one implementation will be registered
- /// although no error will be thrown.
- ///
- /// Predicate to determine if a particular type should be registered
- public void AutoRegister(Func registrationPredicate)
- {
-#if APPDOMAIN_GETASSEMBLIES
- AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, registrationPredicate);
-#else
- AutoRegisterInternal(new Assembly[] { this.GetType().Assembly()}, true, registrationPredicate);
-#endif
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
- ///
- /// What action to take when encountering duplicate implementations of an interface/base class.
- ///
- public void AutoRegister(DuplicateImplementationActions duplicateAction)
- {
-#if APPDOMAIN_GETASSEMBLIES
- AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, null);
-#else
- AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, null);
-#endif
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.
- /// Types will only be registered if they pass the supplied registration predicate.
- ///
- /// What action to take when encountering duplicate implementations of an interface/base class.
- /// Predicate to determine if a particular type should be registered
- ///
- public void AutoRegister(DuplicateImplementationActions duplicateAction, Func registrationPredicate)
- {
-#if APPDOMAIN_GETASSEMBLIES
- AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, registrationPredicate);
-#else
- AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, registrationPredicate);
-#endif
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
- ///
- /// If more than one class implements an interface then only one implementation will be registered
- /// although no error will be thrown.
- ///
- /// Assemblies to process
- public void AutoRegister(IEnumerable assemblies)
- {
- AutoRegisterInternal(assemblies, DuplicateImplementationActions.RegisterSingle, null);
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
- /// Types will only be registered if they pass the supplied registration predicate.
- ///
- /// If more than one class implements an interface then only one implementation will be registered
- /// although no error will be thrown.
- ///
- /// Assemblies to process
- /// Predicate to determine if a particular type should be registered
- public void AutoRegister(IEnumerable assemblies, Func registrationPredicate)
- {
- AutoRegisterInternal(assemblies, DuplicateImplementationActions.RegisterSingle, registrationPredicate);
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
- ///
- /// Assemblies to process
- /// What action to take when encountering duplicate implementations of an interface/base class.
- ///
- public void AutoRegister(IEnumerable assemblies, DuplicateImplementationActions duplicateAction)
- {
- AutoRegisterInternal(assemblies, duplicateAction, null);
- }
-
- ///
- /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies
- /// Types will only be registered if they pass the supplied registration predicate.
- ///
- /// Assemblies to process
- /// What action to take when encountering duplicate implementations of an interface/base class.
- /// Predicate to determine if a particular type should be registered
- ///
- public void AutoRegister(IEnumerable assemblies, DuplicateImplementationActions duplicateAction, Func registrationPredicate)
- {
- AutoRegisterInternal(assemblies, duplicateAction, registrationPredicate);
- }
-
- ///
- /// Creates/replaces a container class registration with default options.
- ///
- /// Type to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType)
- {
- return RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerType));
- }
-
- ///
- /// Creates/replaces a named container class registration with default options.
- ///
- /// Type to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, string name)
- {
- return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType));
- }
-
- ///
- /// Creates/replaces a container class registration with a given implementation and default options.
- ///
- /// Type to register
- /// Type to instantiate that implements RegisterType
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Type registerImplementation)
- {
- return this.RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation));
- }
-
- ///
- /// Creates/replaces a named container class registration with a given implementation and default options.
- ///
- /// Type to register
- /// Type to instantiate that implements RegisterType
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Type registerImplementation, string name)
- {
- return this.RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation));
- }
-
- ///
- /// Creates/replaces a container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Instance of RegisterType to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, object instance)
- {
- return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerType, instance));
- }
-
- ///
- /// Creates/replaces a named container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Instance of RegisterType to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, object instance, string name)
- {
- return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerType, instance));
- }
-
- ///
- /// Creates/replaces a container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Type of instance to register that implements RegisterType
- /// Instance of RegisterImplementation to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Type registerImplementation, object instance)
- {
- return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerImplementation, instance));
- }
-
- ///
- /// Creates/replaces a named container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Type of instance to register that implements RegisterType
- /// Instance of RegisterImplementation to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Type registerImplementation, object instance, string name)
- {
- return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerImplementation, instance));
- }
-
- ///
- /// Creates/replaces a container class registration with a user specified factory
- ///
- /// Type to register
- /// Factory/lambda that returns an instance of RegisterType
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Func factory)
- {
- return RegisterInternal(registerType, string.Empty, new DelegateFactory(registerType, factory));
- }
-
- ///
- /// Creates/replaces a container class registration with a user specified factory
- ///
- /// Type to register
- /// Factory/lambda that returns an instance of RegisterType
- /// Name of registation
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Type registerType, Func factory, string name)
- {
- return RegisterInternal(registerType, name, new DelegateFactory(registerType, factory));
- }
-
- ///
- /// Creates/replaces a container class registration with default options.
- ///
- /// Type to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register()
- where RegisterType : class
- {
- return this.Register(typeof(RegisterType));
- }
-
- ///
- /// Creates/replaces a named container class registration with default options.
- ///
- /// Type to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(string name)
- where RegisterType : class
- {
- return this.Register(typeof(RegisterType), name);
- }
-
- ///
- /// Creates/replaces a container class registration with a given implementation and default options.
- ///
- /// Type to register
- /// Type to instantiate that implements RegisterType
- /// RegisterOptions for fluent API
- public RegisterOptions Register()
- where RegisterType : class
- where RegisterImplementation : class, RegisterType
- {
- return this.Register(typeof(RegisterType), typeof(RegisterImplementation));
- }
-
- ///
- /// Creates/replaces a named container class registration with a given implementation and default options.
- ///
- /// Type to register
- /// Type to instantiate that implements RegisterType
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(string name)
- where RegisterType : class
- where RegisterImplementation : class, RegisterType
- {
- return this.Register(typeof(RegisterType), typeof(RegisterImplementation), name);
- }
-
- ///
- /// Creates/replaces a container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Instance of RegisterType to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register(RegisterType instance)
- where RegisterType : class
- {
- return this.Register(typeof(RegisterType), instance);
- }
-
- ///
- /// Creates/replaces a named container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Instance of RegisterType to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(RegisterType instance, string name)
- where RegisterType : class
- {
- return this.Register(typeof(RegisterType), instance, name);
- }
-
- ///
- /// Creates/replaces a container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Type of instance to register that implements RegisterType
- /// Instance of RegisterImplementation to register
- /// RegisterOptions for fluent API
- public RegisterOptions Register(RegisterImplementation instance)
- where RegisterType : class
- where RegisterImplementation : class, RegisterType
- {
- return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance);
- }
-
- ///
- /// Creates/replaces a named container class registration with a specific, strong referenced, instance.
- ///
- /// Type to register
- /// Type of instance to register that implements RegisterType
- /// Instance of RegisterImplementation to register
- /// Name of registration
- /// RegisterOptions for fluent API
- public RegisterOptions Register(RegisterImplementation instance, string name)
- where RegisterType : class
- where RegisterImplementation : class, RegisterType
- {
- return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name);
- }
-
- ///
- /// Creates/replaces a container class registration with a user specified factory
- ///
- /// Type to register
- /// Factory/lambda that returns an instance of RegisterType
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Func factory)
- where RegisterType : class
- {
- if (factory == null)
- {
- throw new ArgumentNullException("factory");
- }
-
- return this.Register(typeof(RegisterType), (c, o) => factory(c, o));
- }
-
- ///
- /// Creates/replaces a named container class registration with a user specified factory
- ///
- /// Type to register
- /// Factory/lambda that returns an instance of RegisterType
- /// Name of registation
- /// RegisterOptions for fluent API
- public RegisterOptions Register(Func factory, string name)
- where RegisterType : class
- {
- if (factory == null)
- {
- throw new ArgumentNullException("factory");
- }
-
- return this.Register(typeof(RegisterType), (c, o) => factory(c, o), name);
- }
-
- ///
- /// Register multiple implementations of a type.
- ///
- /// Internally this registers each implementation using the full name of the class as its registration name.
- ///
- /// Type that each implementation implements
- /// Types that implement RegisterType
- /// MultiRegisterOptions for the fluent API
- public MultiRegisterOptions RegisterMultiple(IEnumerable implementationTypes)
- {
- return RegisterMultiple(typeof(RegisterType), implementationTypes);
- }
-
- ///
- /// Register multiple implementations of a type.
- ///
- /// Internally this registers each implementation using the full name of the class as its registration name.
- ///
- /// Type that each implementation implements
- /// Types that implement RegisterType
- /// MultiRegisterOptions for the fluent API
- public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable implementationTypes)
- {
- if (implementationTypes == null)
- throw new ArgumentNullException("types", "types is null.");
-
- foreach (var type in implementationTypes)
-
- //#if NETFX_CORE
- // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
- //#else
- if (!registrationType.IsAssignableFrom(type))
-
- //#endif
- throw new ArgumentException(string.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName));
-
- if (implementationTypes.Count() != implementationTypes.Distinct().Count())
- {
- var queryForDuplicatedTypes = from i in implementationTypes
- group i by i
- into j
- where j.Count() > 1
- select j.Key.FullName;
-
- var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray());
- var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes);
- throw new ArgumentException(multipleRegMessage);
- }
-
- var registerOptions = new List();
-
- foreach (var type in implementationTypes)
- {
- registerOptions.Add(Register(registrationType, type, type.FullName));
- }
-
- return new MultiRegisterOptions(registerOptions);
- }
- #endregion
-
- #region Resolution
- ///
- /// Attempts to resolve a type using default options.
- ///
- /// Type to resolve
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType)
- {
- return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to resolve a type using specified options.
- ///
- /// Type to resolve
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, ResolveOptions options)
- {
- return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, string name)
- {
- return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to resolve a type using supplied options and name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, string name, ResolveOptions options)
- {
- return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, NamedParameterOverloads parameters)
- {
- return ResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to resolve a type using specified options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)
- {
- return ResolveInternal(new TypeRegistration(resolveType), parameters, options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied constructor parameters and name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Name of registration
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters)
- {
- return ResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to resolve a named type using specified options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)
- {
- return ResolveInternal(new TypeRegistration(resolveType, name), parameters, options);
- }
-
- ///
- /// Attempts to resolve a type using default options.
- ///
- /// Type to resolve
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve()
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType));
- }
-
- ///
- /// Attempts to resolve a type using specified options.
- ///
- /// Type to resolve
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(ResolveOptions options)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(string name)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), name);
- }
-
- ///
- /// Attempts to resolve a type using supplied options and name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(string name, ResolveOptions options)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), name, options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(NamedParameterOverloads parameters)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), parameters);
- }
-
- ///
- /// Attempts to resolve a type using specified options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(NamedParameterOverloads parameters, ResolveOptions options)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), parameters, options);
- }
-
- ///
- /// Attempts to resolve a type using default options and the supplied constructor parameters and name.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Name of registration
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(string name, NamedParameterOverloads parameters)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), name, parameters);
- }
-
- ///
- /// Attempts to resolve a named type using specified options and the supplied constructor parameters.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Instance of type
- /// Unable to resolve the type.
- public ResolveType Resolve(string name, NamedParameterOverloads parameters, ResolveOptions options)
- where ResolveType : class
- {
- return (ResolveType)Resolve(typeof(ResolveType), name, parameters, options);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with default options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType)
- {
- return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with default options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Bool indicating whether the type can be resolved
- private bool CanResolve(Type resolveType, string name)
- {
- return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the specified options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, ResolveOptions options)
- {
- return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the specified options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, string name, ResolveOptions options)
- {
- return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// User supplied named parameter overloads
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, NamedParameterOverloads parameters)
- {
- return CanResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// User supplied named parameter overloads
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters)
- {
- return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// User supplied named parameter overloads
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)
- {
- return CanResolveInternal(new TypeRegistration(resolveType), parameters, options);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// User supplied named parameter overloads
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)
- {
- return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, options);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with default options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Bool indicating whether the type can be resolved
- public bool CanResolve()
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType));
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with default options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(string name)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), name);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the specified options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(ResolveOptions options)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), options);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the specified options.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(string name, ResolveOptions options)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), name, options);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// User supplied named parameter overloads
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(NamedParameterOverloads parameters)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), parameters);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// User supplied named parameter overloads
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(string name, NamedParameterOverloads parameters)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), name, parameters);
- }
-
- ///
- /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// User supplied named parameter overloads
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(NamedParameterOverloads parameters, ResolveOptions options)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), parameters, options);
- }
-
- ///
- /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.
- ///
- /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).
- /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.
- ///
- /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.
- ///
- /// Type to resolve
- /// Name of registration
- /// User supplied named parameter overloads
- /// Resolution options
- /// Bool indicating whether the type can be resolved
- public bool CanResolve(string name, NamedParameterOverloads parameters, ResolveOptions options)
- where ResolveType : class
- {
- return CanResolve(typeof(ResolveType), name, parameters, options);
- }
-
- ///
- /// Attemps to resolve a type using the default options
- ///
- /// Type to resolve
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the given options
- ///
- /// Type to resolve
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, ResolveOptions options, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and given name
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, string name, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, name);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the given options and name
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, string name, ResolveOptions options, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, name, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and supplied constructor parameters
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, parameters);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and supplied name and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, name, parameters);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the supplied options and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, parameters, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the supplied name, options and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)
- {
- try
- {
- resolvedType = Resolve(resolveType, name, parameters, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = null;
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options
- ///
- /// Type to resolve
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve();
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the given options
- ///
- /// Type to resolve
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(ResolveOptions options, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and given name
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(string name, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(name);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the given options and name
- ///
- /// Type to resolve
- /// Name of registration
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(string name, ResolveOptions options, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(name, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and supplied constructor parameters
- ///
- /// Type to resolve
- /// User specified constructor parameters
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(NamedParameterOverloads parameters, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(parameters);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the default options and supplied name and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(string name, NamedParameterOverloads parameters, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(name, parameters);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the supplied options and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(parameters, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Attemps to resolve a type using the supplied name, options and constructor parameters
- ///
- /// Type to resolve
- /// Name of registration
- /// User specified constructor parameters
- /// Resolution options
- /// Resolved type or default if resolve fails
- /// True if resolved sucessfully, false otherwise
- public bool TryResolve(string name, NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)
- where ResolveType : class
- {
- try
- {
- resolvedType = Resolve(name, parameters, options);
- return true;
- }
- catch (TinyIoCResolutionException)
- {
- resolvedType = default(ResolveType);
- return false;
- }
- }
-
- ///
- /// Returns all registrations of a type
- ///
- /// Type to resolveAll
- /// Whether to include un-named (default) registrations
- /// IEnumerable
- public IEnumerable