vendredi 12 mai 2017

Cannot create an instance of an interface C#

I am having an issue when trying to add an interface to a list of base interfaces when the base interface is of a certain type.

My interfaces are defined as below:

    public interface IWorkspace<out TWorkspace> where TWorkspace : IWorkspaceBaseModel { }
    public interface IWorkspaceBaseModel : IViewBaseModel { }
    public interface ILogCollectionViewModel : IWorkspace<IWorkspaceBaseModel> { }

I use the following code to get all the interfaces:

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
       var workspaces = assembly
          .GetTypes()
          .Where(t => typeof(IWorkspace<IWorkspaceBaseModel>).IsAssignableFrom(t) && t.IsInterface)
          .ToList();

       if (workspaces.Count > 0)
          foreach (var wvm in workspaces)
          {
             var myInterface = (IWorkspaceBaseModel)Activator.CreateInstance(wvm);
          }
    }

I am getting the error "Cannot create an instance of an interface." and when I the the following code:

    var myInterface = (IWorkspace<IWorkspaceBaseModel>)Activator.CreateInstance(wvm);

What i want to do then is add the interface to a list of base interfaces when the have been created:

    var viewList = new List<IWorkspaceBaseModel>();

    viewList.Add(myInterface);    

Any help on how to fix this or a better way of doing it would be greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire