using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using CTA.FeatureDetection.Common.Exceptions;
using CTA.FeatureDetection.Common.Models.Configuration;
using CTA.FeatureDetection.Common.Models.Enums;
using CTA.FeatureDetection.Common.Models.Features.Base;
[assembly: InternalsVisibleTo("CTA.FeatureDetection.Tests")]
namespace CTA.FeatureDetection.Load.Factories
{
internal class CompiledFeatureFactory
{
///
/// Factory method that dynamically instantiates feature classes using assembly and class metadata
///
/// The scope in which to look for this feature
/// Assembly containing the feature type
/// Namespace containing the feature type
/// Metadata about the feature type
/// Instance of the specified feature
public static CompiledFeature GetInstance(FeatureScope featureScope, Assembly assembly, string @namespace, CompiledFeatureMetadata featureMetadata)
{
var fullyQualifiedClassName = $"{@namespace}.{featureMetadata.ClassName}";
var featureType = assembly.GetType(fullyQualifiedClassName);
if (featureType == null)
{
throw new ClassNotFoundException(assembly, fullyQualifiedClassName);
}
try
{
var name = featureMetadata.Name;
var scope = featureScope;
var featureInstance = GetInstance(featureType, name, scope);
return featureInstance;
}
catch (InvalidFeatureException)
{
throw new InvalidFeatureException(assembly, fullyQualifiedClassName);
}
}
///
/// Factory method that dynamically instantiates a feature object by its type
///
/// Type of feature to instantiate
/// Name of feature
/// The scope in which to look for this feature
/// Feature instance
public static CompiledFeature GetInstance(Type featureType, string name, FeatureScope featureScope)
{
if (!(Activator.CreateInstance(featureType) is CompiledFeature featureInstance))
{
throw new InvalidFeatureException(featureType);
}
featureInstance.Name = name;
featureInstance.FeatureScope = featureScope;
return featureInstance;
}
///
/// Factory method that dynamically instantiates a feature object by its type
///
/// Type of feature to instantiate
/// Feature instance
public static CompiledFeature GetInstance(Type featureType)
{
if (!(Activator.CreateInstance(featureType) is CompiledFeature featureInstance))
{
throw new InvalidFeatureException(featureType);
}
return featureInstance;
}
}
}