I trying to use factory pattern to get instance of a class using generics. Not sure what I'm missing the code below.
namespace ConsoleApplication1
{
public interface IResult
{
}
public class ResultA : IResult
{
public string P1 { get; set; }
}
public interface IService<T> where T : IResult
{
T DoWork();
}
public class ServiceA<T> : IService<T> where T : ResultA, IResult, new()
{
public T DoWork()
{
var t = new T();
t.P1 = "value1";
return t;
}
}
public interface IFactory
{
T GetService<T>(string documentType) where T : IService<IResult>;
}
public class MyFactory : IFactory
{
public T GetService<T>(string documentType) where T : IService<IResult>
{
// based on documenet type I will be returning the instances of service here
// im getting error at this line
return new ServiceA<ResultA>(); }
}
}
Error 1 Cannot implicitly convert type 'ConsoleApplication1.ServiceA' to 'T'
Update1
this didn't work either
public interface IFactory
{
IService<IResult> GetService(string documentType);
}
public class MyFactory : IFactory
{
public IService<IResult> GetService(string documentType)
{
return new ServiceA<ResultA>();
}
}