mercredi 22 mai 2019

Factory to return an implementation of Generic

I am trying to return an implementation of generic abstract class using a factory, so that the caller doesn't need to know what the concrete type returned. But failed.

The entity classes

public class Car:IMoveable    { }
public interface IMoveable    { }

The service classes

public abstract class Service<TEntity>
{
   public abstract void PerformService(TEntity t);
}

public class VehicleService : Service<IMoveable>
{
     public override void PerformService(IMoveable t) {     }
}

public class DefaultService : Service<object>
{
     public override void PerformService(object t){  }
}

The factory:

public static class ServiceFactory
{
   public static Service<TEntity> CreateService<TEntity>(TEntity entity) where TEntity : class
   {
      if (typeof(IMoveable).IsAssignableFrom(typeof(TEntity)))
      {
          // run time error here as returns null
          return  new VehicleService() as Service<TEntity>;
          //compiler error
          return (Service<TEntity>) new VehicleService();
      }
      else
      {
         return new DefaultService() as Service<TEntity>;
      }
   }
}

The calling code

static void Main(string[] args)
{
   var car = new Car();
   var service = ServiceFactory.CreateService(car);
}

The problem is the service after createService is always null.

I suspect the problem is TEntity is passed as Car, whereas the VehicleService is implemented as IMovebale. But just can't get my head around how to do it, or is it even possible?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire