I have these interfaces:
public interface _IService<T>
{
T Get(int id);
Task<T> SaveAsync(T entity);
Task<bool> DeleteAsync(int id);
}
public interface ICustomerService :
IService<Customer>
{
IEnumerable<Customer> GetMany(IEnumerable<int> ids);
}
I also have an abstract class and a concrete class:
public abstract class Service : IDisposable
{
protected readonly IUnitOfWork unitOfWork;
protected Service(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public void Dispose()
{
if (unitOfWork != null)
{
unitOfWork.Dispose();
}
}
}
public class CustomerService : Service, ICustomerService
{
public CustomerService(IUnitOfWork unitOfWork)
: base(unitOfWork)
{ }
//Implementation here...
}
Everything works as expected.
Now I want to add generic factory pattern to instantiate various services. So I tried to do:
public TService GetService<TService>()
{
object[] args = new object[] { (unitOfWork) };
return (TService)Activator.CreateInstance(typeof(TService), args);
}
And used as follows:
var customerService = GetService<ICustomerService>();
However, the following exception is thrown:
Constructor on type 'ICustomerService' not found.
So how can I correctly instantiate a class from the interface?