view Implab.ServiceHost/Unity/ConfigurationContext.cs @ 272:9d1cca834b05 v3

preview version of Unity xml configuration
author cin
date Thu, 26 Apr 2018 03:14:54 +0300
parents ade80d94dfb5
children
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Implab.Diagnostics;

namespace Implab.ServiceHost.Unity {
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using global::Unity;
    using global::Unity.Registration;
    using Implab.Xml;
    using static Trace<ConfigurationContext>;

    public class ConfigurationContext {

        readonly TypeResolver m_resolver;

        readonly UnityContainer m_container;

        public ConfigurationContext(UnityContainer container) {
            m_container = container ?? new UnityContainer();
            m_resolver = new TypeResolver();
        }


        public Type Resolve(string typeReference) {
            return m_resolver.Resolve(TypeReference.Parse(typeReference));
        }

        internal void Visit(RegisterElement descriptor) {
            var registrationContext = new RegistrationContext(m_resolver, descriptor.ProvidesType, descriptor.ImplementationType);

            if (descriptor.Injectors != null) {
                foreach (var injector in descriptor.Injectors) {
                    injector.Visit(registrationContext);
                }
            }

            m_container.RegisterType(
                registrationContext.RegistrationType,
                registrationContext.ImplementationType,
                descriptor.Name,
                descriptor.Lifetime?.GetLifetimeManager(this),
                registrationContext.Injections
            );

        }

        internal void Visit(NamespaceElement namespaceElement) {
            m_resolver.AddNamespace(namespaceElement.Name);
        }

        internal void Visit(AssemblyElement assemblyElement) {
            Assembly.Load(assemblyElement.AssemblyName);
        }

        internal void Visit(IncludeElement includeElement) {
            Include(includeElement.Href);
        }

        public void Include(string file) {
            var includeContext = new ConfigurationContext(m_container);
            includeContext.LoadConfig(file);
        }

        public void LoadConfig(string file) {
            var config = SerializationHelpers.DeserializeFromFile<ContainerElement>(file);
            Visit(config);
        }

        public void Visit(ContainerElement containerElement) {
            foreach (var item in containerElement.Items)
                item.Visit(this);
        }

    }
}