This commit is contained in:
2019-12-04 18:57:18 +01:00
parent 4692422c9a
commit 6263791dff
225 changed files with 33065 additions and 2 deletions
@@ -0,0 +1,743 @@
namespace Swan.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
/// <summary>
/// The concrete implementation of a simple IoC container
/// based largely on TinyIoC (https://github.com/grumpydev/TinyIoC).
/// </summary>
/// <seealso cref="System.IDisposable" />
public partial class DependencyContainer : IDisposable
{
private readonly object _autoRegisterLock = new object();
private bool _disposed;
static DependencyContainer()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainer"/> class.
/// </summary>
public DependencyContainer()
{
RegisteredTypes = new TypesConcurrentDictionary(this);
Register(this);
}
private DependencyContainer(DependencyContainer parent)
: this()
{
Parent = parent;
}
/// <summary>
/// Lazy created Singleton instance of the container for simple scenarios.
/// </summary>
public static DependencyContainer Current { get; } = new DependencyContainer();
internal DependencyContainer Parent { get; }
internal TypesConcurrentDictionary RegisteredTypes { get; }
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
foreach (var disposable in RegisteredTypes.Values.Select(item => item as IDisposable))
{
disposable?.Dispose();
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Gets the child container.
/// </summary>
/// <returns>A new instance of the <see cref="DependencyContainer"/> class.</returns>
public DependencyContainer GetChildContainer() => new DependencyContainer(this);
#region Registration
/// <summary>
/// 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.
/// </summary>
/// <param name="duplicateAction">What action to take when encountering duplicate implementations of an interface/base class.</param>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered.</param>
public void AutoRegister(
DependencyContainerDuplicateImplementationAction duplicateAction =
DependencyContainerDuplicateImplementationAction.RegisterSingle,
Func<Type, bool> registrationPredicate = null)
{
AutoRegister(
AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)),
duplicateAction,
registrationPredicate);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="assemblies">Assemblies to process.</param>
/// <param name="duplicateAction">What action to take when encountering duplicate implementations of an interface/base class.</param>
/// <param name="registrationPredicate">Predicate to determine if a particular type should be registered.</param>
public void AutoRegister(
IEnumerable<Assembly> assemblies,
DependencyContainerDuplicateImplementationAction duplicateAction =
DependencyContainerDuplicateImplementationAction.RegisterSingle,
Func<Type, bool> registrationPredicate = null)
{
lock (_autoRegisterLock)
{
var types = assemblies
.SelectMany(a => a.GetAllTypes())
.Where(t => !IsIgnoredType(t, registrationPredicate))
.ToList();
var concreteTypes = types
.Where(type =>
type.IsClass && !type.IsAbstract &&
(type != GetType() && (type.DeclaringType != GetType()) && !type.IsGenericTypeDefinition))
.ToList();
foreach (var type in concreteTypes)
{
try
{
RegisteredTypes.Register(type, string.Empty, GetDefaultObjectFactory(type, type));
}
catch (MethodAccessException)
{
// Ignore methods we can't access - added for Silverlight
}
}
var abstractInterfaceTypes = types.Where(
type =>
((type.IsInterface || type.IsAbstract) && (type.DeclaringType != GetType()) &&
(!type.IsGenericTypeDefinition)));
foreach (var type in abstractInterfaceTypes)
{
var localType = type;
var implementations = concreteTypes
.Where(implementationType => localType.IsAssignableFrom(implementationType)).ToList();
if (implementations.Skip(1).Any())
{
if (duplicateAction == DependencyContainerDuplicateImplementationAction.Fail)
throw new DependencyContainerRegistrationException(type, implementations);
if (duplicateAction == DependencyContainerDuplicateImplementationAction.RegisterMultiple)
{
RegisterMultiple(type, implementations);
}
}
var firstImplementation = implementations.FirstOrDefault();
if (firstImplementation == null) continue;
try
{
RegisteredTypes.Register(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation));
}
catch (MethodAccessException)
{
// Ignore methods we can't access - added for Silverlight
}
}
}
}
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <param name="registerType">Type to register.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register(Type registerType, string name = "")
=> RegisteredTypes.Register(
registerType,
name,
GetDefaultObjectFactory(registerType, registerType));
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <param name="registerType">Type to register.</param>
/// <param name="registerImplementation">Type to instantiate that implements RegisterType.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register(Type registerType, Type registerImplementation, string name = "") =>
RegisteredTypes.Register(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation));
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register.</param>
/// <param name="instance">Instance of RegisterType to register.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register(Type registerType, object instance, string name = "") =>
RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerType, instance));
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <param name="registerType">Type to register.</param>
/// <param name="registerImplementation">Type of instance to register that implements RegisterType.</param>
/// <param name="instance">Instance of RegisterImplementation to register.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register(
Type registerType,
Type registerImplementation,
object instance,
string name = "")
=> RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerImplementation, instance));
/// <summary>
/// Creates/replaces a container class registration with a user specified factory.
/// </summary>
/// <param name="registerType">Type to register.</param>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register(
Type registerType,
Func<DependencyContainer, Dictionary<string, object>, object> factory,
string name = "")
=> RegisteredTypes.Register(registerType, name, new DelegateFactory(registerType, factory));
/// <summary>
/// Creates/replaces a named container class registration with default options.
/// </summary>
/// <typeparam name="TRegister">Type to register.</typeparam>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register<TRegister>(string name = "")
where TRegister : class
{
return Register(typeof(TRegister), name);
}
/// <summary>
/// Creates/replaces a named container class registration with a given implementation and default options.
/// </summary>
/// <typeparam name="TRegister">Type to register.</typeparam>
/// <typeparam name="TRegisterImplementation">Type to instantiate that implements RegisterType.</typeparam>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register<TRegister, TRegisterImplementation>(string name = "")
where TRegister : class
where TRegisterImplementation : class, TRegister
{
return Register(typeof(TRegister), typeof(TRegisterImplementation), name);
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="TRegister">Type to register.</typeparam>
/// <param name="instance">Instance of RegisterType to register.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register<TRegister>(TRegister instance, string name = "")
where TRegister : class
{
return Register(typeof(TRegister), instance, name);
}
/// <summary>
/// Creates/replaces a named container class registration with a specific, strong referenced, instance.
/// </summary>
/// <typeparam name="TRegister">Type to register.</typeparam>
/// <typeparam name="TRegisterImplementation">Type of instance to register that implements RegisterType.</typeparam>
/// <param name="instance">Instance of RegisterImplementation to register.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register<TRegister, TRegisterImplementation>(TRegisterImplementation instance,
string name = "")
where TRegister : class
where TRegisterImplementation : class, TRegister
{
return Register(typeof(TRegister), typeof(TRegisterImplementation), instance, name);
}
/// <summary>
/// Creates/replaces a named container class registration with a user specified factory.
/// </summary>
/// <typeparam name="TRegister">Type to register.</typeparam>
/// <param name="factory">Factory/lambda that returns an instance of RegisterType.</param>
/// <param name="name">Name of registration.</param>
/// <returns>RegisterOptions for fluent API.</returns>
public RegisterOptions Register<TRegister>(
Func<DependencyContainer, Dictionary<string, object>, TRegister> factory, string name = "")
where TRegister : class
{
if (factory == null)
throw new ArgumentNullException(nameof(factory));
return Register(typeof(TRegister), factory, name);
}
/// <summary>
/// Register multiple implementations of a type.
///
/// Internally this registers each implementation using the full name of the class as its registration name.
/// </summary>
/// <typeparam name="TRegister">Type that each implementation implements.</typeparam>
/// <param name="implementationTypes">Types that implement RegisterType.</param>
/// <returns>MultiRegisterOptions for the fluent API.</returns>
public MultiRegisterOptions RegisterMultiple<TRegister>(IEnumerable<Type> implementationTypes) =>
RegisterMultiple(typeof(TRegister), implementationTypes);
/// <summary>
/// Register multiple implementations of a type.
///
/// Internally this registers each implementation using the full name of the class as its registration name.
/// </summary>
/// <param name="registrationType">Type that each implementation implements.</param>
/// <param name="implementationTypes">Types that implement RegisterType.</param>
/// <returns>MultiRegisterOptions for the fluent API.</returns>
public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable<Type> implementationTypes)
{
if (implementationTypes == null)
throw new ArgumentNullException(nameof(implementationTypes), "types is null.");
foreach (var type in implementationTypes.Where(type => !registrationType.IsAssignableFrom(type)))
{
throw new ArgumentException(
$"types: The type {registrationType.FullName} is not assignable from {type.FullName}");
}
if (implementationTypes.Count() != implementationTypes.Distinct().Count())
{
var queryForDuplicatedTypes = implementationTypes
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(j => j.Key.FullName);
var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray());
throw new ArgumentException(
$"types: The same implementation type cannot be specified multiple times for {registrationType.FullName}\n\n{fullNamesOfDuplicatedTypes}");
}
var registerOptions = implementationTypes
.Select(type => Register(registrationType, type, type.FullName))
.ToList();
return new MultiRegisterOptions(registerOptions);
}
#endregion
#region Unregistration
/// <summary>
/// Remove a named container class registration.
/// </summary>
/// <typeparam name="TRegister">Type to unregister.</typeparam>
/// <param name="name">Name of registration.</param>
/// <returns><c>true</c> if the registration is successfully found and removed; otherwise, <c>false</c>.</returns>
public bool Unregister<TRegister>(string name = "") => Unregister(typeof(TRegister), name);
/// <summary>
/// Remove a named container class registration.
/// </summary>
/// <param name="registerType">Type to unregister.</param>
/// <param name="name">Name of registration.</param>
/// <returns><c>true</c> if the registration is successfully found and removed; otherwise, <c>false</c>.</returns>
public bool Unregister(Type registerType, string name = "") =>
RegisteredTypes.RemoveRegistration(new TypeRegistration(registerType, name));
#endregion
#region Resolution
/// <summary>
/// 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.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="name">Name of registration.</param>
/// <param name="options">Resolution options.</param>
/// <returns>Instance of type.</returns>
/// <exception cref="DependencyContainerResolutionException">Unable to resolve the type.</exception>
public object Resolve(
Type resolveType,
string name = null,
DependencyContainerResolveOptions options = null)
=> RegisteredTypes.ResolveInternal(new TypeRegistration(resolveType, name), options ?? DependencyContainerResolveOptions.Default);
/// <summary>
/// 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.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="name">Name of registration.</param>
/// <param name="options">Resolution options.</param>
/// <returns>Instance of type.</returns>
/// <exception cref="DependencyContainerResolutionException">Unable to resolve the type.</exception>
public TResolveType Resolve<TResolveType>(
string name = null,
DependencyContainerResolveOptions options = null)
where TResolveType : class
{
return (TResolveType)Resolve(typeof(TResolveType), name, options);
}
/// <summary>
/// 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 registrations fail to construct objects when called.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="name">The name.</param>
/// <param name="options">Resolution options.</param>
/// <returns>
/// Bool indicating whether the type can be resolved.
/// </returns>
public bool CanResolve(
Type resolveType,
string name = null,
DependencyContainerResolveOptions options = null) =>
RegisteredTypes.CanResolve(new TypeRegistration(resolveType, name), options);
/// <summary>
/// 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 registrations fail to construct objects when called.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="name">Name of registration.</param>
/// <param name="options">Resolution options.</param>
/// <returns>Bool indicating whether the type can be resolved.</returns>
public bool CanResolve<TResolveType>(
string name = null,
DependencyContainerResolveOptions options = null)
where TResolveType : class
{
return CanResolve(typeof(TResolveType), name, options);
}
/// <summary>
/// Attempts to resolve a type using the default options.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve(Type resolveType, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the given options.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="options">Resolution options.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve(Type resolveType, DependencyContainerResolveOptions options, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, options: options);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the default options and given name.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="name">Name of registration.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve(Type resolveType, string name, out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the given options and name.
/// </summary>
/// <param name="resolveType">Type to resolve.</param>
/// <param name="name">Name of registration.</param>
/// <param name="options">Resolution options.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve(
Type resolveType,
string name,
DependencyContainerResolveOptions options,
out object resolvedType)
{
try
{
resolvedType = Resolve(resolveType, name, options);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = null;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the default options.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve<TResolveType>(out TResolveType resolvedType)
where TResolveType : class
{
try
{
resolvedType = Resolve<TResolveType>();
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = default;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the given options.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="options">Resolution options.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve<TResolveType>(DependencyContainerResolveOptions options, out TResolveType resolvedType)
where TResolveType : class
{
try
{
resolvedType = Resolve<TResolveType>(options: options);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = default;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the default options and given name.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="name">Name of registration.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve<TResolveType>(string name, out TResolveType resolvedType)
where TResolveType : class
{
try
{
resolvedType = Resolve<TResolveType>(name);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = default;
return false;
}
}
/// <summary>
/// Attempts to resolve a type using the given options and name.
/// </summary>
/// <typeparam name="TResolveType">Type to resolve.</typeparam>
/// <param name="name">Name of registration.</param>
/// <param name="options">Resolution options.</param>
/// <param name="resolvedType">Resolved type or default if resolve fails.</param>
/// <returns><c>true</c> if resolved successfully, <c>false</c> otherwise.</returns>
public bool TryResolve<TResolveType>(
string name,
DependencyContainerResolveOptions options,
out TResolveType resolvedType)
where TResolveType : class
{
try
{
resolvedType = Resolve<TResolveType>(name, options);
return true;
}
catch (DependencyContainerResolutionException)
{
resolvedType = default;
return false;
}
}
/// <summary>
/// Returns all registrations of a type.
/// </summary>
/// <param name="resolveType">Type to resolveAll.</param>
/// <param name="includeUnnamed">Whether to include un-named (default) registrations.</param>
/// <returns>IEnumerable.</returns>
public IEnumerable<object> ResolveAll(Type resolveType, bool includeUnnamed = false)
=> RegisteredTypes.Resolve(resolveType, includeUnnamed);
/// <summary>
/// Returns all registrations of a type.
/// </summary>
/// <typeparam name="TResolveType">Type to resolveAll.</typeparam>
/// <param name="includeUnnamed">Whether to include un-named (default) registrations.</param>
/// <returns>IEnumerable.</returns>
public IEnumerable<TResolveType> ResolveAll<TResolveType>(bool includeUnnamed = true)
where TResolveType : class
{
return ResolveAll(typeof(TResolveType), includeUnnamed).Cast<TResolveType>();
}
/// <summary>
/// Attempts to resolve all public property dependencies on the given object using the given resolve options.
/// </summary>
/// <param name="input">Object to "build up".</param>
/// <param name="resolveOptions">Resolve options to use.</param>
public void BuildUp(object input, DependencyContainerResolveOptions resolveOptions = null)
{
if (resolveOptions == null)
resolveOptions = DependencyContainerResolveOptions.Default;
var properties = input.GetType()
.GetProperties()
.Where(property => property.GetCacheGetMethod() != null && property.GetCacheSetMethod() != null &&
!property.PropertyType.IsValueType);
foreach (var property in properties.Where(property => property.GetValue(input, null) == null))
{
try
{
property.SetValue(
input,
RegisteredTypes.ResolveInternal(new TypeRegistration(property.PropertyType), resolveOptions),
null);
}
catch (DependencyContainerResolutionException)
{
// Catch any resolution errors and ignore them
}
}
}
#endregion
#region Internal Methods
internal static bool IsValidAssignment(Type registerType, Type registerImplementation)
{
if (!registerType.IsGenericTypeDefinition)
{
if (!registerType.IsAssignableFrom(registerImplementation))
return false;
}
else
{
if (registerType.IsInterface && registerImplementation.GetInterfaces().All(t => t.Name != registerType.Name))
return false;
if (registerType.IsAbstract && registerImplementation.BaseType != registerType)
return false;
}
return true;
}
private static bool IsIgnoredAssembly(Assembly assembly)
{
// TODO - find a better way to remove "system" assemblies from the auto registration
var ignoreChecks = new List<Func<Assembly, bool>>
{
asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal),
asm => asm.FullName.StartsWith("xunit.", StringComparison.Ordinal),
};
return ignoreChecks.Any(check => check(assembly));
}
private static bool IsIgnoredType(Type type, Func<Type, bool> registrationPredicate)
{
// TODO - find a better way to remove "system" types from the auto registration
var ignoreChecks = new List<Func<Type, bool>>()
{
t => t.FullName?.StartsWith("System.", StringComparison.Ordinal) ?? false,
t => t.FullName?.StartsWith("Microsoft.", StringComparison.Ordinal) ?? false,
t => t.IsPrimitive,
t => t.IsGenericTypeDefinition,
t => (t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0) &&
!(t.IsInterface || t.IsAbstract),
};
if (registrationPredicate != null)
{
ignoreChecks.Add(t => !registrationPredicate(t));
}
return ignoreChecks.Any(check => check(type));
}
private static ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) => registerType.IsInterface || registerType.IsAbstract
? (ObjectFactoryBase)new SingletonFactory(registerType, registerImplementation)
: new MultiInstanceFactory(registerType, registerImplementation);
#endregion
}
}
@@ -0,0 +1,46 @@
namespace Swan.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Generic Constraint Registration Exception.
/// </summary>
/// <seealso cref="Exception" />
public class DependencyContainerRegistrationException : Exception
{
private const string ConvertErrorText = "Cannot convert current registration of {0} to {1}";
private const string RegisterErrorText =
"Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}.";
private const string ErrorText = "Duplicate implementation of type {0} found ({1}).";
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainerRegistrationException"/> class.
/// </summary>
/// <param name="registerType">Type of the register.</param>
/// <param name="types">The types.</param>
public DependencyContainerRegistrationException(Type registerType, IEnumerable<Type> types)
: base(string.Format(ErrorText, registerType, GetTypesString(types)))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainerRegistrationException" /> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="method">The method.</param>
/// <param name="isTypeFactory">if set to <c>true</c> [is type factory].</param>
public DependencyContainerRegistrationException(Type type, string method, bool isTypeFactory = false)
: base(isTypeFactory
? string.Format(RegisterErrorText, type.FullName, method)
: string.Format(ConvertErrorText, type.FullName, method))
{
}
private static string GetTypesString(IEnumerable<Type> types)
{
return string.Join(",", types.Select(type => type.FullName));
}
}
}
@@ -0,0 +1,31 @@
namespace Swan.DependencyInjection
{
using System;
/// <summary>
/// An exception for dependency resolutions.
/// </summary>
/// <seealso cref="System.Exception" />
[Serializable]
public class DependencyContainerResolutionException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainerResolutionException"/> class.
/// </summary>
/// <param name="type">The type.</param>
public DependencyContainerResolutionException(Type type)
: base($"Unable to resolve type: {type.FullName}")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainerResolutionException"/> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="innerException">The inner exception.</param>
public DependencyContainerResolutionException(Type type, Exception innerException)
: base($"Unable to resolve type: {type.FullName}", innerException)
{
}
}
}
@@ -0,0 +1,114 @@
namespace Swan.DependencyInjection
{
using System.Collections.Generic;
/// <summary>
/// Resolution settings.
/// </summary>
public class DependencyContainerResolveOptions
{
/// <summary>
/// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found).
/// </summary>
public static DependencyContainerResolveOptions Default { get; } = new DependencyContainerResolveOptions();
/// <summary>
/// Gets or sets the unregistered resolution action.
/// </summary>
/// <value>
/// The unregistered resolution action.
/// </value>
public DependencyContainerUnregisteredResolutionAction UnregisteredResolutionAction { get; set; } =
DependencyContainerUnregisteredResolutionAction.AttemptResolve;
/// <summary>
/// Gets or sets the named resolution failure action.
/// </summary>
/// <value>
/// The named resolution failure action.
/// </value>
public DependencyContainerNamedResolutionFailureAction NamedResolutionFailureAction { get; set; } =
DependencyContainerNamedResolutionFailureAction.Fail;
/// <summary>
/// Gets the constructor parameters.
/// </summary>
/// <value>
/// The constructor parameters.
/// </value>
public Dictionary<string, object> ConstructorParameters { get; } = new Dictionary<string, object>();
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public DependencyContainerResolveOptions Clone() => new DependencyContainerResolveOptions
{
NamedResolutionFailureAction = NamedResolutionFailureAction,
UnregisteredResolutionAction = UnregisteredResolutionAction,
};
}
/// <summary>
/// Defines Resolution actions.
/// </summary>
public enum DependencyContainerUnregisteredResolutionAction
{
/// <summary>
/// Attempt to resolve type, even if the type isn't registered.
///
/// Registered types/options will always take precedence.
/// </summary>
AttemptResolve,
/// <summary>
/// Fail resolution if type not explicitly registered
/// </summary>
Fail,
/// <summary>
/// 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.
/// </summary>
GenericsOnly,
}
/// <summary>
/// Enumerates failure actions.
/// </summary>
public enum DependencyContainerNamedResolutionFailureAction
{
/// <summary>
/// The attempt unnamed resolution
/// </summary>
AttemptUnnamedResolution,
/// <summary>
/// The fail
/// </summary>
Fail,
}
/// <summary>
/// Enumerates duplicate definition actions.
/// </summary>
public enum DependencyContainerDuplicateImplementationAction
{
/// <summary>
/// The register single
/// </summary>
RegisterSingle,
/// <summary>
/// The register multiple
/// </summary>
RegisterMultiple,
/// <summary>
/// The fail
/// </summary>
Fail,
}
}
@@ -0,0 +1,22 @@
namespace Swan.DependencyInjection
{
using System;
/// <summary>
/// Weak Reference Exception.
/// </summary>
/// <seealso cref="System.Exception" />
public class DependencyContainerWeakReferenceException : Exception
{
private const string ErrorText = "Unable to instantiate {0} - referenced object has been reclaimed";
/// <summary>
/// Initializes a new instance of the <see cref="DependencyContainerWeakReferenceException"/> class.
/// </summary>
/// <param name="type">The type.</param>
public DependencyContainerWeakReferenceException(Type type)
: base(string.Format(ErrorText, type.FullName))
{
}
}
}
@@ -0,0 +1,423 @@
namespace Swan.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// Represents an abstract class for Object Factory.
/// </summary>
public abstract class ObjectFactoryBase
{
/// <summary>
/// Whether to assume this factory successfully constructs its objects
///
/// Generally set to true for delegate style factories as CanResolve cannot delve
/// into the delegates they contain.
/// </summary>
public virtual bool AssumeConstruction => false;
/// <summary>
/// The type the factory instantiates.
/// </summary>
public abstract Type CreatesType { get; }
/// <summary>
/// Constructor to use, if specified.
/// </summary>
public ConstructorInfo Constructor { get; private set; }
/// <summary>
/// Gets the singleton variant.
/// </summary>
/// <value>
/// The singleton variant.
/// </value>
/// <exception cref="DependencyContainerRegistrationException">singleton.</exception>
public virtual ObjectFactoryBase SingletonVariant =>
throw new DependencyContainerRegistrationException(GetType(), "singleton");
/// <summary>
/// Gets the multi instance variant.
/// </summary>
/// <value>
/// The multi instance variant.
/// </value>
/// <exception cref="DependencyContainerRegistrationException">multi-instance.</exception>
public virtual ObjectFactoryBase MultiInstanceVariant =>
throw new DependencyContainerRegistrationException(GetType(), "multi-instance");
/// <summary>
/// Gets the strong reference variant.
/// </summary>
/// <value>
/// The strong reference variant.
/// </value>
/// <exception cref="DependencyContainerRegistrationException">strong reference.</exception>
public virtual ObjectFactoryBase StrongReferenceVariant =>
throw new DependencyContainerRegistrationException(GetType(), "strong reference");
/// <summary>
/// Gets the weak reference variant.
/// </summary>
/// <value>
/// The weak reference variant.
/// </value>
/// <exception cref="DependencyContainerRegistrationException">weak reference.</exception>
public virtual ObjectFactoryBase WeakReferenceVariant =>
throw new DependencyContainerRegistrationException(GetType(), "weak reference");
/// <summary>
/// Create the type.
/// </summary>
/// <param name="requestedType">Type user requested to be resolved.</param>
/// <param name="container">Container that requested the creation.</param>
/// <param name="options">The options.</param>
/// <returns> Instance of type. </returns>
public abstract object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options);
/// <summary>
/// Gets the factory for child container.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="parent">The parent.</param>
/// <param name="child">The child.</param>
/// <returns></returns>
public virtual ObjectFactoryBase GetFactoryForChildContainer(
Type type,
DependencyContainer parent,
DependencyContainer child)
{
return this;
}
}
/// <inheritdoc />
/// <summary>
/// IObjectFactory that creates new instances of types for each resolution.
/// </summary>
internal class MultiInstanceFactory : ObjectFactoryBase
{
private readonly Type _registerType;
private readonly Type _registerImplementation;
public MultiInstanceFactory(Type registerType, Type registerImplementation)
{
if (registerImplementation.IsAbstract || registerImplementation.IsInterface)
{
throw new DependencyContainerRegistrationException(registerImplementation,
"MultiInstanceFactory",
true);
}
if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation))
{
throw new DependencyContainerRegistrationException(registerImplementation,
"MultiInstanceFactory",
true);
}
_registerType = registerType;
_registerImplementation = registerImplementation;
}
public override Type CreatesType => _registerImplementation;
public override ObjectFactoryBase SingletonVariant =>
new SingletonFactory(_registerType, _registerImplementation);
public override ObjectFactoryBase MultiInstanceVariant => this;
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
try
{
return container.RegisteredTypes.ConstructType(_registerImplementation, Constructor, options);
}
catch (DependencyContainerResolutionException ex)
{
throw new DependencyContainerResolutionException(_registerType, ex);
}
}
}
/// <inheritdoc />
/// <summary>
/// IObjectFactory that invokes a specified delegate to construct the object.
/// </summary>
internal class DelegateFactory : ObjectFactoryBase
{
private readonly Type _registerType;
private readonly Func<DependencyContainer, Dictionary<string, object>, object> _factory;
public DelegateFactory(
Type registerType,
Func<DependencyContainer, Dictionary<string, object>, object> factory)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_registerType = registerType;
}
public override bool AssumeConstruction => true;
public override Type CreatesType => _registerType;
public override ObjectFactoryBase WeakReferenceVariant => new WeakDelegateFactory(_registerType, _factory);
public override ObjectFactoryBase StrongReferenceVariant => this;
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
try
{
return _factory.Invoke(container, options.ConstructorParameters);
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(_registerType, ex);
}
}
}
/// <inheritdoc />
/// <summary>
/// IObjectFactory that invokes a specified delegate to construct the object
/// Holds the delegate using a weak reference.
/// </summary>
internal class WeakDelegateFactory : ObjectFactoryBase
{
private readonly Type _registerType;
private readonly WeakReference _factory;
public WeakDelegateFactory(
Type registerType,
Func<DependencyContainer, Dictionary<string, object>, object> factory)
{
if (factory == null)
throw new ArgumentNullException(nameof(factory));
_factory = new WeakReference(factory);
_registerType = registerType;
}
public override bool AssumeConstruction => true;
public override Type CreatesType => _registerType;
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
if (!(_factory.Target is Func<DependencyContainer, Dictionary<string, object>, object> factory))
throw new DependencyContainerWeakReferenceException(_registerType);
return new DelegateFactory(_registerType, factory);
}
}
public override ObjectFactoryBase WeakReferenceVariant => this;
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
if (!(_factory.Target is Func<DependencyContainer, Dictionary<string, object>, object> factory))
throw new DependencyContainerWeakReferenceException(_registerType);
try
{
return factory.Invoke(container, options.ConstructorParameters);
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(_registerType, ex);
}
}
}
/// <summary>
/// Stores an particular instance to return for a type.
/// </summary>
internal class InstanceFactory : ObjectFactoryBase, IDisposable
{
private readonly Type _registerType;
private readonly Type _registerImplementation;
private readonly object _instance;
public InstanceFactory(Type registerType, Type registerImplementation, object instance)
{
if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation))
throw new DependencyContainerRegistrationException(registerImplementation, "InstanceFactory", true);
_registerType = registerType;
_registerImplementation = registerImplementation;
_instance = instance;
}
public override bool AssumeConstruction => true;
public override Type CreatesType => _registerImplementation;
public override ObjectFactoryBase MultiInstanceVariant =>
new MultiInstanceFactory(_registerType, _registerImplementation);
public override ObjectFactoryBase WeakReferenceVariant =>
new WeakInstanceFactory(_registerType, _registerImplementation, _instance);
public override ObjectFactoryBase StrongReferenceVariant => this;
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
return _instance;
}
public void Dispose()
{
var disposable = _instance as IDisposable;
disposable?.Dispose();
}
}
/// <summary>
/// Stores the instance with a weak reference.
/// </summary>
internal class WeakInstanceFactory : ObjectFactoryBase, IDisposable
{
private readonly Type _registerType;
private readonly Type _registerImplementation;
private readonly WeakReference _instance;
public WeakInstanceFactory(Type registerType, Type registerImplementation, object instance)
{
if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation))
{
throw new DependencyContainerRegistrationException(
registerImplementation,
"WeakInstanceFactory",
true);
}
_registerType = registerType;
_registerImplementation = registerImplementation;
_instance = new WeakReference(instance);
}
public override Type CreatesType => _registerImplementation;
public override ObjectFactoryBase MultiInstanceVariant =>
new MultiInstanceFactory(_registerType, _registerImplementation);
public override ObjectFactoryBase WeakReferenceVariant => this;
public override ObjectFactoryBase StrongReferenceVariant
{
get
{
var instance = _instance.Target;
if (instance == null)
throw new DependencyContainerWeakReferenceException(_registerType);
return new InstanceFactory(_registerType, _registerImplementation, instance);
}
}
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
var instance = _instance.Target;
if (instance == null)
throw new DependencyContainerWeakReferenceException(_registerType);
return instance;
}
public void Dispose() => (_instance.Target as IDisposable)?.Dispose();
}
/// <summary>
/// A factory that lazy instantiates a type and always returns the same instance.
/// </summary>
internal class SingletonFactory : ObjectFactoryBase, IDisposable
{
private readonly Type _registerType;
private readonly Type _registerImplementation;
private readonly object _singletonLock = new object();
private object _current;
public SingletonFactory(Type registerType, Type registerImplementation)
{
if (registerImplementation.IsAbstract || registerImplementation.IsInterface)
{
throw new DependencyContainerRegistrationException(registerImplementation, nameof(SingletonFactory), true);
}
if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation))
{
throw new DependencyContainerRegistrationException(registerImplementation, nameof(SingletonFactory), true);
}
_registerType = registerType;
_registerImplementation = registerImplementation;
}
public override Type CreatesType => _registerImplementation;
public override ObjectFactoryBase SingletonVariant => this;
public override ObjectFactoryBase MultiInstanceVariant =>
new MultiInstanceFactory(_registerType, _registerImplementation);
public override object GetObject(
Type requestedType,
DependencyContainer container,
DependencyContainerResolveOptions options)
{
if (options.ConstructorParameters.Count != 0)
throw new ArgumentException("Cannot specify parameters for singleton types");
lock (_singletonLock)
{
if (_current == null)
_current = container.RegisteredTypes.ConstructType(_registerImplementation, Constructor, options);
}
return _current;
}
public override ObjectFactoryBase GetFactoryForChildContainer(
Type type,
DependencyContainer parent,
DependencyContainer child)
{
// We make sure that the singleton is constructed before the child container takes the factory.
// Otherwise the results would vary depending on whether or not the parent container had resolved
// the type before the child container does.
GetObject(type, parent, DependencyContainerResolveOptions.Default);
return this;
}
public void Dispose() => (_current as IDisposable)?.Dispose();
}
}
+131
View File
@@ -0,0 +1,131 @@
namespace Swan.DependencyInjection
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Registration options for "fluent" API.
/// </summary>
public sealed class RegisterOptions
{
private readonly TypesConcurrentDictionary _registeredTypes;
private readonly DependencyContainer.TypeRegistration _registration;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterOptions" /> class.
/// </summary>
/// <param name="registeredTypes">The registered types.</param>
/// <param name="registration">The registration.</param>
public RegisterOptions(TypesConcurrentDictionary registeredTypes, DependencyContainer.TypeRegistration registration)
{
_registeredTypes = registeredTypes;
_registration = registration;
}
/// <summary>
/// Make registration a singleton (single instance) if possible.
/// </summary>
/// <returns>A registration options for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic constraint registration exception.</exception>
public RegisterOptions AsSingleton()
{
var currentFactory = _registeredTypes.GetCurrentFactory(_registration);
if (currentFactory == null)
throw new DependencyContainerRegistrationException(_registration.Type, "singleton");
return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.SingletonVariant);
}
/// <summary>
/// Make registration multi-instance if possible.
/// </summary>
/// <returns>A registration options for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic constraint registration exception.</exception>
public RegisterOptions AsMultiInstance()
{
var currentFactory = _registeredTypes.GetCurrentFactory(_registration);
if (currentFactory == null)
throw new DependencyContainerRegistrationException(_registration.Type, "multi-instance");
return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.MultiInstanceVariant);
}
/// <summary>
/// Make registration hold a weak reference if possible.
/// </summary>
/// <returns>A registration options for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic constraint registration exception.</exception>
public RegisterOptions WithWeakReference()
{
var currentFactory = _registeredTypes.GetCurrentFactory(_registration);
if (currentFactory == null)
throw new DependencyContainerRegistrationException(_registration.Type, "weak reference");
return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.WeakReferenceVariant);
}
/// <summary>
/// Make registration hold a strong reference if possible.
/// </summary>
/// <returns>A registration options for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic constraint registration exception.</exception>
public RegisterOptions WithStrongReference()
{
var currentFactory = _registeredTypes.GetCurrentFactory(_registration);
if (currentFactory == null)
throw new DependencyContainerRegistrationException(_registration.Type, "strong reference");
return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.StrongReferenceVariant);
}
}
/// <summary>
/// Registration options for "fluent" API when registering multiple implementations.
/// </summary>
public sealed class MultiRegisterOptions
{
private IEnumerable<RegisterOptions> _registerOptions;
/// <summary>
/// Initializes a new instance of the <see cref="MultiRegisterOptions"/> class.
/// </summary>
/// <param name="registerOptions">The register options.</param>
public MultiRegisterOptions(IEnumerable<RegisterOptions> registerOptions)
{
_registerOptions = registerOptions;
}
/// <summary>
/// Make registration a singleton (single instance) if possible.
/// </summary>
/// <returns>A registration multi-instance for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic Constraint Registration Exception.</exception>
public MultiRegisterOptions AsSingleton()
{
_registerOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton());
return this;
}
/// <summary>
/// Make registration multi-instance if possible.
/// </summary>
/// <returns>A registration multi-instance for fluent API.</returns>
/// <exception cref="DependencyContainerRegistrationException">Generic Constraint Registration Exception.</exception>
public MultiRegisterOptions AsMultiInstance()
{
_registerOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance());
return this;
}
private IEnumerable<RegisterOptions> ExecuteOnAllRegisterOptions(
Func<RegisterOptions, RegisterOptions> action)
{
return _registerOptions.Select(action).ToList();
}
}
}
@@ -0,0 +1,67 @@
namespace Swan.DependencyInjection
{
using System;
public partial class DependencyContainer
{
/// <summary>
/// Represents a Type Registration within the IoC Container.
/// </summary>
public sealed class TypeRegistration
{
private readonly int _hashCode;
/// <summary>
/// Initializes a new instance of the <see cref="TypeRegistration"/> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="name">The name.</param>
public TypeRegistration(Type type, string name = null)
{
Type = type;
Name = name ?? string.Empty;
_hashCode = string.Concat(Type.FullName, "|", Name).GetHashCode();
}
/// <summary>
/// Gets the type.
/// </summary>
/// <value>
/// The type.
/// </value>
public Type Type { get; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; }
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (!(obj is TypeRegistration typeRegistration) || typeRegistration.Type != Type)
return false;
return string.Compare(Name, typeRegistration.Name, StringComparison.Ordinal) == 0;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() => _hashCode;
}
}
}
@@ -0,0 +1,351 @@
namespace Swan.DependencyInjection
{
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
/// <summary>
/// Represents a Concurrent Dictionary for TypeRegistration.
/// </summary>
public class TypesConcurrentDictionary : ConcurrentDictionary<DependencyContainer.TypeRegistration, ObjectFactoryBase>
{
private static readonly ConcurrentDictionary<ConstructorInfo, ObjectConstructor> ObjectConstructorCache =
new ConcurrentDictionary<ConstructorInfo, ObjectConstructor>();
private readonly DependencyContainer _dependencyContainer;
internal TypesConcurrentDictionary(DependencyContainer dependencyContainer)
{
_dependencyContainer = dependencyContainer;
}
/// <summary>
/// Represents a delegate to build an object with the parameters.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The built object.</returns>
public delegate object ObjectConstructor(params object[] parameters);
internal IEnumerable<object> Resolve(Type resolveType, bool includeUnnamed)
{
var registrations = Keys.Where(tr => tr.Type == resolveType)
.Concat(GetParentRegistrationsForType(resolveType)).Distinct();
if (!includeUnnamed)
registrations = registrations.Where(tr => !string.IsNullOrEmpty(tr.Name));
return registrations.Select(registration =>
ResolveInternal(registration, DependencyContainerResolveOptions.Default));
}
internal ObjectFactoryBase GetCurrentFactory(DependencyContainer.TypeRegistration registration)
{
TryGetValue(registration, out var current);
return current;
}
internal RegisterOptions Register(Type registerType, string name, ObjectFactoryBase factory)
=> AddUpdateRegistration(new DependencyContainer.TypeRegistration(registerType, name), factory);
internal RegisterOptions AddUpdateRegistration(DependencyContainer.TypeRegistration typeRegistration, ObjectFactoryBase factory)
{
this[typeRegistration] = factory;
return new RegisterOptions(this, typeRegistration);
}
internal bool RemoveRegistration(DependencyContainer.TypeRegistration typeRegistration)
=> TryRemove(typeRegistration, out _);
internal object ResolveInternal(
DependencyContainer.TypeRegistration registration,
DependencyContainerResolveOptions? options = null)
{
if (options == null)
options = DependencyContainerResolveOptions.Default;
// Attempt container resolution
if (TryGetValue(registration, out var factory))
{
try
{
return factory.GetObject(registration.Type, _dependencyContainer, options);
}
catch (DependencyContainerResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(registration.Type, ex);
}
}
// Attempt to get a factory from parent if we can
var bubbledObjectFactory = GetParentObjectFactory(registration);
if (bubbledObjectFactory != null)
{
try
{
return bubbledObjectFactory.GetObject(registration.Type, _dependencyContainer, options);
}
catch (DependencyContainerResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(registration.Type, ex);
}
}
// Fail if requesting named resolution and settings set to fail if unresolved
if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction ==
DependencyContainerNamedResolutionFailureAction.Fail)
throw new DependencyContainerResolutionException(registration.Type);
// Attempted unnamed fallback container resolution if relevant and requested
if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction ==
DependencyContainerNamedResolutionFailureAction.AttemptUnnamedResolution)
{
if (TryGetValue(new DependencyContainer.TypeRegistration(registration.Type, string.Empty), out factory))
{
try
{
return factory.GetObject(registration.Type, _dependencyContainer, options);
}
catch (DependencyContainerResolutionException)
{
throw;
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(registration.Type, ex);
}
}
}
// Attempt unregistered construction if possible and requested
var isValid = (options.UnregisteredResolutionAction ==
DependencyContainerUnregisteredResolutionAction.AttemptResolve) ||
(registration.Type.IsGenericType && options.UnregisteredResolutionAction ==
DependencyContainerUnregisteredResolutionAction.GenericsOnly);
return isValid && !registration.Type.IsAbstract && !registration.Type.IsInterface
? ConstructType(registration.Type, null, options)
: throw new DependencyContainerResolutionException(registration.Type);
}
internal bool CanResolve(
DependencyContainer.TypeRegistration registration,
DependencyContainerResolveOptions? options = null)
{
if (options == null)
options = DependencyContainerResolveOptions.Default;
var checkType = registration.Type;
var name = registration.Name;
if (TryGetValue(new DependencyContainer.TypeRegistration(checkType, name), out var factory))
{
if (factory.AssumeConstruction)
return true;
if (factory.Constructor == null)
return GetBestConstructor(factory.CreatesType, options) != null;
return CanConstruct(factory.Constructor, options);
}
// Fail if requesting named resolution and settings set to fail if unresolved
// Or bubble up if we have a parent
if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction ==
DependencyContainerNamedResolutionFailureAction.Fail)
return _dependencyContainer.Parent?.RegisteredTypes.CanResolve(registration, options.Clone()) ?? false;
// Attempted unnamed fallback container resolution if relevant and requested
if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction ==
DependencyContainerNamedResolutionFailureAction.AttemptUnnamedResolution)
{
if (TryGetValue(new DependencyContainer.TypeRegistration(checkType), out factory))
{
if (factory.AssumeConstruction)
return true;
return GetBestConstructor(factory.CreatesType, options) != null;
}
}
// Check if type is an automatic lazy factory request or an IEnumerable<ResolveType>
if (IsAutomaticLazyFactoryRequest(checkType) || registration.Type.IsIEnumerable())
return true;
// Attempt unregistered construction if possible and requested
// If we cant', bubble if we have a parent
if ((options.UnregisteredResolutionAction ==
DependencyContainerUnregisteredResolutionAction.AttemptResolve) ||
(checkType.IsGenericType && options.UnregisteredResolutionAction ==
DependencyContainerUnregisteredResolutionAction.GenericsOnly))
{
return (GetBestConstructor(checkType, options) != null) ||
(_dependencyContainer.Parent?.RegisteredTypes.CanResolve(registration, options.Clone()) ?? false);
}
// Bubble resolution up the container tree if we have a parent
return _dependencyContainer.Parent != null && _dependencyContainer.Parent.RegisteredTypes.CanResolve(registration, options.Clone());
}
internal object ConstructType(
Type implementationType,
ConstructorInfo constructor,
DependencyContainerResolveOptions? options = null)
{
var typeToConstruct = implementationType;
if (constructor == null)
{
// Try and get the best constructor that we can construct
// if we can't construct any then get the constructor
// with the least number of parameters so we can throw a meaningful
// resolve exception
constructor = GetBestConstructor(typeToConstruct, options) ??
GetTypeConstructors(typeToConstruct).LastOrDefault();
}
if (constructor == null)
throw new DependencyContainerResolutionException(typeToConstruct);
var ctorParams = constructor.GetParameters();
var args = new object?[ctorParams.Length];
for (var parameterIndex = 0; parameterIndex < ctorParams.Length; parameterIndex++)
{
var currentParam = ctorParams[parameterIndex];
try
{
args[parameterIndex] = options?.ConstructorParameters.GetValueOrDefault(currentParam.Name, ResolveInternal(new DependencyContainer.TypeRegistration(currentParam.ParameterType), options.Clone()));
}
catch (DependencyContainerResolutionException ex)
{
// If a constructor parameter can't be resolved
// it will throw, so wrap it and throw that this can't
// be resolved.
throw new DependencyContainerResolutionException(typeToConstruct, ex);
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(typeToConstruct, ex);
}
}
try
{
return CreateObjectConstructionDelegateWithCache(constructor).Invoke(args);
}
catch (Exception ex)
{
throw new DependencyContainerResolutionException(typeToConstruct, ex);
}
}
private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor)
{
if (ObjectConstructorCache.TryGetValue(constructor, out var objectConstructor))
return objectConstructor;
// We could lock the cache here, but there's no real side
// effect to two threads creating the same ObjectConstructor
// at the same time, compared to the cost of a lock for
// every creation.
var constructorParams = constructor.GetParameters();
var lambdaParams = Expression.Parameter(typeof(object[]), "parameters");
var newParams = new Expression[constructorParams.Length];
for (var i = 0; i < constructorParams.Length; i++)
{
var paramsParameter = Expression.ArrayIndex(lambdaParams, Expression.Constant(i));
newParams[i] = Expression.Convert(paramsParameter, constructorParams[i].ParameterType);
}
var newExpression = Expression.New(constructor, newParams);
var constructionLambda = Expression.Lambda(typeof(ObjectConstructor), newExpression, lambdaParams);
objectConstructor = (ObjectConstructor)constructionLambda.Compile();
ObjectConstructorCache[constructor] = objectConstructor;
return objectConstructor;
}
private static IEnumerable<ConstructorInfo> GetTypeConstructors(Type type)
=> type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Length);
private static bool IsAutomaticLazyFactoryRequest(Type type)
{
if (!type.IsGenericType)
return false;
var genericType = type.GetGenericTypeDefinition();
// Just a func
if (genericType == typeof(Func<>))
return true;
// 2 parameter func with string as first parameter (name)
if (genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))
return true;
// 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters)
return genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) &&
type.GetGenericArguments()[1] == typeof(IDictionary<string, object>);
}
private ObjectFactoryBase? GetParentObjectFactory(DependencyContainer.TypeRegistration registration)
{
if (_dependencyContainer.Parent == null)
return null;
return _dependencyContainer.Parent.RegisteredTypes.TryGetValue(registration, out var factory)
? factory.GetFactoryForChildContainer(registration.Type, _dependencyContainer.Parent, _dependencyContainer)
: _dependencyContainer.Parent.RegisteredTypes.GetParentObjectFactory(registration);
}
private ConstructorInfo? GetBestConstructor(
Type type,
DependencyContainerResolveOptions options)
=> type.IsValueType ? null : GetTypeConstructors(type).FirstOrDefault(ctor => CanConstruct(ctor, options));
private bool CanConstruct(
MethodBase ctor,
DependencyContainerResolveOptions? options)
{
foreach (var parameter in ctor.GetParameters())
{
if (string.IsNullOrEmpty(parameter.Name))
return false;
var isParameterOverload = options.ConstructorParameters.ContainsKey(parameter.Name);
if (parameter.ParameterType.IsPrimitive && !isParameterOverload)
return false;
if (!isParameterOverload &&
!CanResolve(new DependencyContainer.TypeRegistration(parameter.ParameterType), options.Clone()))
return false;
}
return true;
}
private IEnumerable<DependencyContainer.TypeRegistration> GetParentRegistrationsForType(Type resolveType)
=> _dependencyContainer.Parent == null
? Array.Empty<DependencyContainer.TypeRegistration>()
: _dependencyContainer.Parent.RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(_dependencyContainer.Parent.RegisteredTypes.GetParentRegistrationsForType(resolveType));
}
}