コード例 #1
0
        /// <summary>
        /// Creates a proxyfied interface according to the given definition.
        /// </summary>
        /// <param name="definition">Definition of the proxy to build.</param>
        /// <param name="initialImplementation">Optional first and available implementation.</param>
        /// <returns></returns>
        internal static ServiceProxyBase CreateProxy(IProxyDefinition definition)
        {
            Debug.Assert(definition.TypeInterface.IsInterface, "This check MUST be done by ProxyDefinition implementation.");

            string dynamicTypeName = String.Format("{0}_Proxy_{1}", definition.TypeInterface.Name, Interlocked.Increment(ref _typeID));

            // Defines a public sealed class that implements typeInterface only.
            TypeBuilder typeBuilder = _moduleBuilder.DefineType(
                dynamicTypeName,
                TypeAttributes.Class | TypeAttributes.Sealed,
                definition.ProxyBase,
                new Type[] { definition.TypeInterface });

            // This defines the IService<typeInterface> interface.
            if (definition.IsDynamicService)
            {
                // Our proxy object will implement both typeInterface and IService<typeInterface> interfaces.
                Type serviceInterfaceType = typeof(IService <>).MakeGenericType(new Type[] { definition.TypeInterface });
                typeBuilder.AddInterfaceImplementation(serviceInterfaceType);
            }

            ProxyGenerator pg = new ProxyGenerator(typeBuilder, definition);

            pg.DefineConstructor();

            pg.DefineServiceProperty();

            pg.DefineImplementationProperty();

            pg.ImplementInterface();

            object unavailableImpl = CreateUnavailableImplementation(definition.TypeInterface, dynamicTypeName + "_UN");

            return(pg.Finalize(unavailableImpl));
        }