lundi 19 novembre 2018

CreateInstance InvalidCastException

There are three builds in my .net core application.

Solution.Models.Customer:

public class Customer : ICustomer
{           
    public void Get()
    {
        Console.WriteLine("Message!");
    }
}

Solution.Interfaces.ICustomer:

public interface ICustomer
{
    void Get();
}

Solution.Creator.ContainerCreator:

public class ContainerCreator
{
    Assembly _assembly;

    public void Add(Assembly assembly)
    {
        _assembly = assembly;
    }

    public object CreateInstance(Type type)
    {
        object instance;

        var classesInfo = GetClassesInfo();
        //classes Info looks for a match in the assembly with the passed parameter.
        var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

        var objectType = result.ClassType;

        instance = Activator.CreateInstance(objectType);

        return instance;
    }
}

Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.

var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Solution.Models.dll",
                SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));

What am I doing wrong and how can I defeat this exception?





Aucun commentaire:

Enregistrer un commentaire