I have the following 3 projects.
Services: In this project I have a number of "service" classes and the following factory class:
public class ServiceFactory : IServiceFactory
{
public TService Get<TEntity, TService>()
where TEntity : class
where TService : IService<TEntity>
{
object[] args = new object[] { };
return (TService)Activator.CreateInstance(typeof(TService), args);
}
}
A service interface looks like this:
public interface ICustomerService : IService<Customer>
{
IEnumerable<Customer> GetAll();
}
Main: The main project implements the services defined in the above project, eg:
public class CustomerService : ICustomerService
{
public IEnumerable<Customer> GetAll()
{
return null;
}
}
Plugins
This project contains plugins and each plugin can use one or more different services. The plugins are loaded using MEF
. A plugin might look like this:
[Export(typeof(IPlugin))]
public class CustomerPlugin : IPlugin
{
private readonly ICustomerService customerService;
public CustomerPlugin (IServiceFactory serviceFactory)
{
customerService = serviceFactory.Get<Customer, CustomerService>();
}
}
Plugins are loaded and created within the main project.
However there is a problem in the above code (in the Plugins project) because the serviceFactory tries to create a concrete implementation, ie. CustomerService, but this is obviously not possible because it's only available in the Main project.
How is it possible to get this factory pattern working?