Esempio n. 1
0
        private object Resolve(Type dependencyType, ImplementationVariant implementationVariant = ImplementationVariant.None)
        {
            if (dependencyType.IsGenericType && (dependencyType.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
            {
                return(GetAllImplementations(dependencyType.GetGenericArguments()[0]));
            }

            if (dependencyType.IsGenericType && dependencies.ContainsKey(dependencyType.GetGenericTypeDefinition()))
            {
                var implementationType = dependencies[dependencyType.GetGenericTypeDefinition()][0].ImplementationType;
                implementationType = implementationType.MakeGenericType(dependencyType.GetGenericArguments());

                if (dependencyType.IsAssignableFrom(implementationType))
                {
                    return(CreateInstance(implementationType));
                }
            }

            if (!dependencies.ContainsKey(dependencyType))
            {
                return(null);
            }

            var implementationInfo = GetImplementationInfo(dependencyType, implementationVariant);

            if (!dependencyType.IsAssignableFrom(implementationInfo.ImplementationType))
            {
                return(null);
            }

            return(implementationInfo.Lifetime switch
            {
                Lifetime.Transient => CreateInstance(implementationInfo.ImplementationType),
                Lifetime.Singleton => Singleton.GetInstance(implementationInfo.ImplementationType, CreateInstance),
                _ => null
            });
 public ImplementationInfo(Type type, Lifetime lifetime, ImplementationVariant variant)
 {
     Lifetime           = lifetime;
     ImplementationType = type;
     Variant            = variant;
 }
        public void Register <TDependency, TImplementation>(Lifetime lifetime = Lifetime.Transient, ImplementationVariant variant = ImplementationVariant.None)
            where TDependency : class
            where TImplementation : TDependency
        {
            var implementationInfo = new ImplementationInfo(typeof(TImplementation), lifetime, variant);

            if (Dependencies.ContainsKey(typeof(TDependency)))
            {
                Dependencies[typeof(TDependency)].Add(implementationInfo);
            }
            else
            {
                Dependencies.Add(typeof(TDependency), new List <ImplementationInfo>());
                Dependencies[typeof(TDependency)].Add(implementationInfo);
            }
        }
Esempio n. 4
0
        public T Resolve <T>(ImplementationVariant implementationVariant = ImplementationVariant.None) where T : class
        {
            Type dependencyType = typeof(T);

            return((T)Resolve(dependencyType, implementationVariant));
        }
 public DependencyKeyAttribute(ImplementationVariant variant)
 {
     ImplementationVariant = variant;
 }