RegistrationBuilder
using Stashbox.Lifetime;
using Stashbox.Registration.Fluent;
using System;
namespace Stashbox.Registration
{
internal static class RegistrationBuilder
{
public static ServiceRegistration BuildServiceRegistration(IContainerContext containerContext, RegistrationConfiguration registrationConfiguration, bool isDecorator)
{
PreProcessExistingInstanceIfNeeded(containerContext, registrationConfiguration.Context, registrationConfiguration.ImplementationType);
if (!isDecorator)
registrationConfiguration.Context.Lifetime = ChooseLifeTime(containerContext, registrationConfiguration.Context);
if (!registrationConfiguration.ImplementationType.IsOpenGenericType())
return new ServiceRegistration(registrationConfiguration.ImplementationType, DetermineRegistrationType(registrationConfiguration), containerContext.ContainerConfiguration.RegistrationBehavior, registrationConfiguration.Context, isDecorator);
return new OpenGenericRegistration(registrationConfiguration.ImplementationType, containerContext.ContainerConfiguration.RegistrationBehavior, registrationConfiguration.Context, isDecorator);
}
private static void PreProcessExistingInstanceIfNeeded(IContainerContext containerContext, RegistrationContext registrationContext, Type implementationType)
{
if (registrationContext.ExistingInstance != null) {
if (!registrationContext.IsLifetimeExternallyOwned && implementationType.IsDisposable())
containerContext.RootScope.AddDisposableTracking(registrationContext.ExistingInstance);
if (registrationContext.Finalizer != null)
containerContext.RootScope.AddWithFinalizer(registrationContext.ExistingInstance, registrationContext.Finalizer);
}
}
private static LifetimeDescriptor ChooseLifeTime(IContainerContext containerContext, RegistrationContext registrationContext)
{
object lifetimeDescriptor;
if (!registrationContext.IsWireUp) {
lifetimeDescriptor = registrationContext.Lifetime;
if (lifetimeDescriptor == null)
return containerContext.ContainerConfiguration.DefaultLifetime;
} else
lifetimeDescriptor = Lifetimes.Singleton;
return (LifetimeDescriptor)lifetimeDescriptor;
}
private static RegistrationType DetermineRegistrationType(RegistrationConfiguration registrationConfiguration)
{
if (registrationConfiguration.Context.ExistingInstance != null) {
if (!registrationConfiguration.Context.IsWireUp)
return RegistrationType.Instance;
return RegistrationType.WireUp;
}
if ((object)registrationConfiguration.Context.Factory == null)
return RegistrationType.Default;
return RegistrationType.Factory;
}
}
}