• Service Locator Pattern in C# with Lazy Initialization(转)


    原文

    In my previous post Service Locator Pattern in C#: A Simple Example I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of lazy initialization.

    Defining Lazy Initialization

    Lazy initialization improves the performance of object creation, deferring long running initializations until they are really needed.

    Suppose for example that some of the fields of an object need to be read from the database. If a client never access those fields, accessing the database to retrieve those fields has been useless and it has just made object initialization slower (often by a considerable factor).

    Martin Fowler credits Kent Beck with the introduction of the lazy initialization pattern, and in PoEAA book he describes it in the following way:

    The basic idea is that every access to the field checks to see if it’s null. If so, it calculates the value of the field before returning the field. To make this work you have to ensure that the field is self-encapsulated, meaning that all access to the field, even from within the class, is done through a getting method.

    Fairly simple.

    The Improved Service Locator

    The following is the improved version of the service locator which uses lazy initialization of the services.

    internal class ServiceLocator : IServiceLocator
    {
        // a map between contracts -> concrete implementation classes
        private IDictionary<Type, Type> servicesType;
    
        // a map containing references to concrete implementation already instantiated
        // (the service locator uses lazy instantiation).
        private IDictionary<Type, object> instantiatedServices;
    
        internal ServiceLocator()
        {
            this.servicesType = new Dictionary<Type, Type>();
            this.instantiatedServices = new Dictionary<Type, object>();
    
            this.BuildServiceTypesMap();
        }
    
        public T GetService<T>()
        {
            if (this.instantiatedServices.ContainsKey(typeof(T)))
            {
                return (T)this.instantiatedServices[typeof(T)];
            }
            else
            {
                // lazy initialization
                try
                {
                    // use reflection to invoke the service
                    ConstructorInfo constructor = servicesType[typeof(T)].GetConstructor(new Type[0]);
                    Debug.Assert(constructor != null, "Cannot find a suitable constructor for " + typeof(T));
    
                    T service = (T)constructor.Invoke(null);
    
                    // add the service to the ones that we have already instantiated
                    instantiatedServices.Add(typeof(T), service);
    
                    return service;
                }
                catch (KeyNotFoundException)
                {
                    throw new ApplicationException"The requested service is not registered");
                }
            }
        }
    
        private void BuildServiceTypesMap()
        {
            servicesType.Add(typeof(IServiceA),
                typeof(ServiceA));
    
            servicesType.Add(typeof(IServiceB),
                typeof(ServiceB));
    
            servicesType.Add(typeof(IServiceC),
                typeof(ServiceC));
         }
    }
    

    We are now maintaining two separate maps:

    • servicesType maps an interface describing a service to a type T that implements that interface.
    • instantiatedServices maps an interface to an instantiated object of class T.

    Both maps are initialized in the constructor. However only the first map is filled. Every time GetService is invoked, we check whether a concrete implementation of that service has already been created. If not, we create that service implementation retrieving its constructor via reflection, and we put a reference to that implementation in the instantiatedServices map.

    For this to work, the service implementation needs to expose a default (parameterless) constructor.

    If services creation time is significant, lazy initialization can save you quite some time during application start up, with very little cost in terms of increased complexity.

    Next article in the series: A Singleton Service Locator

  • 相关阅读:
    C# BulkCopy System.Data.SqlClient 数据库批量添加行数句
    SQL server 数据库优化表
    Bootstrap简介,特点,用法
    Entity Fromwork浅谈
    ADO,net 实体数据模型增、删、改,浅谈
    程序如何适应所有的难产客户
    访问数据库优化
    C#中哈希表(HashTable)的用法详解
    C# winform无边框窗体移动
    函数柯里化之加法add应用---add(1,2) add(1)(2) add(1)(2)(3) add(1,2,3)(4)
  • 原文地址:https://www.cnblogs.com/philzhou/p/1974493.html
Copyright © 2020-2023  润新知