Home > Software design >  How to convert object to specific class with using type information
How to convert object to specific class with using type information

Time:12-05

I have a interface. That interface name is IQueue. Also I have concrete classes. Their names are MyMessage1 and MyMessage2.

public interface IQueue 
{
}

public class MyMessage1 : IQueue 
{
    public string Message { get; set; }
    public DateTime PublishedDate { get; set; }
}

public class MyMessage2 : IQueue 
{
    public string Name { get; set; }
}

I am getting all the concrete classes implemented from IQueue with reflection and create a instance.

var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => typeof(IQueue).IsAssignableFrom(p) && p.IsClass)
    .ToList);

foreach(var type in types) 
{
    var instance = Activator.CreateInstance(type);
}

Instance is an object. How I can cast to specific class without using below code? Is it possible.

(MyMessage1)Activator.CreateInstance(type)
(MyMessage2)Activator.CreateInstance(type)

I want to create a specific class instance using type information

CodePudding user response:

Cast to the type IQueue since all the types you want to instantiate implement that interface.

IQueue instance = (IQueue)Activator.CreateInstance(type);

Add methods and properties you want to use to that interface. The concrete classes will then have to implement these methods and properties and you can access them via the interface.

CodePudding user response:

Copy below code snippet and paste inside your class

internal static void Register(Type interfaceType)
        {
            var interfaceTypes =
                AppDomain.CurrentDomain.GetAssemblies()
                    .SelectMany(s => s.GetTypes())
                    .Where(t => interfaceType.IsAssignableFrom(t)
                                && t.IsClass && !t.IsAbstract)
                    .Select(t => new
                    {
                        parentInterface = t.GetInterfaces().FirstOrDefault(),
                        Implementation = t
                    })
                    .Where(t => t.parentInterface is not null
                                && interfaceType.IsAssignableFrom(t.parentInterface));

            foreach (var type in interfaceTypes)
            {
                var instance = Activator.CreateInstance(type.Implementation);

            }
        }

Use like AddServices(typeof(IQueue));

  • Related