Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create instance from an interface?

Tags:

c#

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?

like image 684
Ivan-Mark Debono Avatar asked Dec 07 '25 09:12

Ivan-Mark Debono


1 Answers

You cannot. You will need an dependency injection container that knows that for each ISomething you want an ConcreteSomething created. This connection between class and interface is not established magically, just imagine you had two classes implementing ISomething.

You can build that container yourself, using a Dictionary of interface type to class type and then doing return (TService)Activator.CreateInstance(this.TypeMappings[typeof(TService)], args); or you could use one of the existing dependency injection containers. But you need this mapping.

like image 92
nvoigt Avatar answered Dec 08 '25 23:12

nvoigt