Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8406843
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T23:13:24+00:00 2026-06-09T23:13:24+00:00

Using TypeGenerator Class public class TypeGenerator { /// <summary> /// internal cache for already

  • 0

Using TypeGenerator Class

   public class TypeGenerator
    {
        /// <summary>
        /// internal cache for already generated types
        /// </summary>
        private static Dictionary<Type, Type> asyncTypeCache = new Dictionary<Type, Type>();      

        /// <summary>
        /// provides a cache for the modules
        /// </summary>
        private static Dictionary<string, ModuleBuilder> moduleBuilderCache = new Dictionary<string, ModuleBuilder>();

        /// <summary>
        /// Generates the Async version of the TSync type.
        /// the generate type repects the AsyncPattern and it is already decorated with attributes for WCF operations
        /// </summary>
        /// <typeparam name="TSync">The Sync version of type</typeparam>
        /// <returns>A type that is the Async version of the TSync type, that implements the AsyncPattern for WCF</returns>
        public Type GenerateAsyncInterfaceFor<TSync>() where TSync : class
        {
            Type syncType = typeof(TSync);

            if (asyncTypeCache.ContainsKey(syncType)) return asyncTypeCache[syncType];

            if (!syncType.IsInterface) throw new InvalidOperationException("Only interface type could be transformed");

            var asynchAssemblyName = string.Format("{0}.Async", syncType.Namespace);

            TypeBuilder typeBuilder =
                GetModuleBuilder(asynchAssemblyName)
                .DefineType(
                    string.Format("{0}.Async.{1}", syncType.Namespace, syncType.Name),
                    (syncType.IsPublic ? TypeAttributes.Public : 0) |
                    TypeAttributes.Abstract |
                    TypeAttributes.Interface);

            foreach (var method in syncType.GetAllInterfaceMethods())
            {
                AddBeginAsynchVersionForMethod(typeBuilder, method, @"http://tempuri.org");
                AddEndAsynchVersionForMethod(typeBuilder, method);
            }

            var serviceContractConstructor = typeof(ServiceContractAttribute).GetConstructor(new Type[0]);
            var attribuiteBuilder =
                new CustomAttributeBuilder(
                    serviceContractConstructor,
                    new object[0]);

            typeBuilder.SetCustomAttribute(attribuiteBuilder);

            Type asyncType = typeBuilder.CreateType();

            asyncTypeCache.Add(syncType, asyncType);
            return asyncType;
        }

        /// <summary>
        /// Creates a End verison of a sync method, that implements the AsyncPattern
        /// </summary>
        /// <param name="typeBuilder">the tipebuilder where the type is being building</param>
        /// <param name="method">information about the sync version of the method</param>
        private void AddEndAsynchVersionForMethod(TypeBuilder typeBuilder, MethodInfo method)
        {
            string endMethodName = string.Format("End{0}", method.Name);

            var parameters =
                method.GetParameters()
                .Select(x =>
                    new
                    {
                        Type = x.ParameterType,
                        Name = x.Name,
                        Attributes = x.Attributes,
                    })
                .ToList();

            parameters.Add(
                new
                {
                    Type = typeof(IAsyncResult),
                    Name = "asyncResult",
                    Attributes = ParameterAttributes.None,
                });

            var methodBuilder =
                typeBuilder
                .DefineMethod(
                    endMethodName,
                    method.Attributes,
                    method.CallingConvention,
                    method.ReturnType,
                    parameters.Select(x => x.Type).ToArray());

            for (int i = 0; i < parameters.Count(); i++)
            {
                var parameter = parameters[i];
                methodBuilder.DefineParameter(i + 1, parameter.Attributes, parameter.Name);             
            }
        }

        /// <summary>
        /// Creates a Begin verison of a sync method, that implements the AsyncPattern
        /// </summary>
        /// <param name="typeBuilder">the tipebuilder where the type is being building</param>
        /// <param name="method">information about the sync version of the method</param>
        private void AddBeginAsynchVersionForMethod(TypeBuilder typeBuilder, MethodInfo method, string nameSpace)
        {
            string beginMethodName = string.Format("Begin{0}", method.Name);

            var parametersTypeList = method.GetParameters().Select(x => x.ParameterType).ToList();
            var parametersNameList = method.GetParameters().Select(x => x.Name).ToList();
            var parametersAttributeList = method.GetParameters().Select(x => x.Attributes).ToList();

            parametersTypeList.Add(typeof(AsyncCallback));
            parametersAttributeList.Add(ParameterAttributes.None);
            parametersNameList.Add("callBack");

            parametersTypeList.Add(typeof(object));
            parametersAttributeList.Add(ParameterAttributes.None);
            parametersNameList.Add("statusObject");

            var methodBuilder = 
                typeBuilder
                .DefineMethod(
                    beginMethodName,
                    method.Attributes,
                    method.CallingConvention,
                    typeof(IAsyncResult),
                    parametersTypeList.ToArray());

            for (int i = 0; i < parametersTypeList.Count(); i++)
            {
                methodBuilder.DefineParameter(i + 1, parametersAttributeList[i], parametersNameList[i]);
            }

            var operationContractConstructor = typeof(OperationContractAttribute).GetConstructor(new Type[0]);
            var asynchPatternProperty = typeof(OperationContractAttribute).GetProperty("AsyncPattern");

            var actionProperty = typeof(OperationContractAttribute).GetProperty("Action");
            var actionValue = string.Format("{0}/{1}/{2}", nameSpace, method.DeclaringType.Name, method.Name);

            var replyActionProperty = typeof(OperationContractAttribute).GetProperty("ReplyAction");
            var replyActionValue = string.Format("{0}/{1}/{2}Response", nameSpace, method.DeclaringType.Name, method.Name);

            var attribuiteBuilder = 
                new CustomAttributeBuilder(
                    operationContractConstructor, 
                    new object[0],
                    new[] { asynchPatternProperty, actionProperty, replyActionProperty },
                    new object[] { true, actionValue, replyActionValue });



            methodBuilder.SetCustomAttribute(attribuiteBuilder);
        }

        /// <summary>
        /// provides a ModelBuilder with the required assembly name
        /// </summary>
        /// <param name="requiredAssemblyName">the assembly name for where the type will be generated in</param>
        /// <returns>a model builder</returns>
        /// <remarks>in this version the model builder is not cached, it could be interesting to generate all the types in the same assembly by caching the model builder</remarks>
        private ModuleBuilder GetModuleBuilder(string requiredAssemblyName)
        {
            if (moduleBuilderCache.ContainsKey(requiredAssemblyName))
            {
                return moduleBuilderCache[requiredAssemblyName];
            }

            AssemblyName assemblyName = new AssemblyName(requiredAssemblyName);
            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    assemblyName,
                    AssemblyBuilderAccess.Run);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

            moduleBuilderCache[requiredAssemblyName] = moduleBuilder;

            return moduleBuilder;
        }
    }

and TypeExtentions Class

public static class TypeExtensions
    {
        /// <summary>
        /// extracts all the methods fromthe given interface type and from all the inherited ones too
        /// </summary>
        /// <param name="type">the type fromwhich extracts all the methods</param>
        /// <returns>list of MemberInfo representing the methods</returns>
        public static IEnumerable<MethodInfo> GetAllInterfaceMethods(this Type type)
        {

            IEnumerable<MethodInfo> methods = type.GetMethods();
            foreach (var subType in type.GetInterfaces())
            {
                methods = methods.Union(GetAllInterfaceMethods(subType));
            }
            return methods;
        }
    }

I ‘m able to convert a Synchronous Interface to Asynchronous one.

How to use DuplexChannelFactory with a pre-defined reflection Asynchronous interface ?

var myInterface = new TypeGenerator ( ) . GenerateAsyncInterfaceFor<mySynchronousInterface> ( );

var Client = new DuplexChannelFactory<myInterface> ( new InstanceContext ( new myClass ( ) ) , "myConfiguration" );

I’m getting the following issue:

The type or namespace name ‘myInterface’ could not be found (are you
missing a using directive or an assembly reference?)

I’m trying to code a mid-tier WCF interface.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T23:13:26+00:00Added an answer on June 9, 2026 at 11:13 pm

    The syntax you are using is for compile time typing, of course the types you are making are generated at runtime, so it isn’t going to work. It is possible though.
    How to: Examine and Instantiate Generic Types with Reflection

    Here’s how the code will look (I’m assuming myClass was already defined with source code, if not it would just be another Activator.CreateInstance call)

    Type t = typeof(DuplexChannelFactory<>);
    Type typedDuplexChannelFactory = t.MakeGenericType(new Type[]{myInterface});
    var Client = Activator.CreateInstance(typedDuplexChannelFactory, new object[]{new InstanceContext ( new myClass ( ) ) , "myConfiguration"});
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using a populated Table Type as the source for a TSQL-Merge. I want to
Using doxygen and graphviz with my C# project, I can generate class diagrams in
Using C#, I need a class called User that has a username, password, active
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Program { class
Using a CSS image sprite, I'm creating an 'interactive' image where hovering over certain
using this http://bl.ocks.org/950642 we can see how to add images to nodes, the question
Using SQL Server 2008 R2 we are looking for a way to select the
Using CI for the first time and i'm smashing my head with this seemingly
Using the Redis info command, I am able to get all the stats of
Using Location.getBearing(); I seem to get randomly changing bearings. Aka, I can turn the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.