Use the Factory Pattern to create your instance(s). I would refactor your code as below.
Introduce a service which ochestrate calls to Repo and the factory you created. The service, I refer to as ICustomerProcessor. (ICusomerService is probably not the right choice of word here). This processor, you factory, and the repository is dependency injected, using your IUnityContainer. Some do call this as Facade.
public interface ICustomerProcessor {
IEnumerable<Customer> GetAll();
}
The implementation of this service would simply call the Repository to get data, and a factory to create the entities.
public class CustomerProcessor : ICustomerProcessor {
private readonly ICustomerFactory _customerFactory;
private readonly ICustomerRepository _customerRepository;
public CustomerProcessor(ICustomerRepository customerRepository, ICustomerFactory customerFactory)
{
_customerRepository = customerRepository;
_customerFactory = customerFactory;
}
public IEnumerable<Customer> GetAll()
{
var data = _customerRepository.GetDataTable();
return _customerFactory.CreateCustomers(data);
}
}
The repository only a representation of your database, and it just abstract your db call.
public class CustomerRepository : ICustomerRepository
{
private readonly IDatabaseContext _database;
public CustomerRepository(IDatabaseContext database) {
_database = database;
}
public DataTable GetDataTable() {
DataTable dtResult;
using (DbCommand cmd = _database.GetStoredProcCommand("spSelectAllCustomer"))
{
dtResult = _database.ExecuteDataSet(cmd).Tables[0];
}
return dtResult;
}
}
Note that IDatabaseContext does not require to Dependency Injected, it can be just a static context which you call the db. But the key idea is that your Repository encapsulate the database operations but nothing else.
With regards to Container.Resolve :
You don't need this as your service are injected via the contructore inject. You domain object should not be dependency injected. They are just entities.
With regards to Service Locator.
It is not the service locator is anti-patten, it is the way people use it make it an anti-pattern. In your case there absolutely no need to have a service locator in context. But in some case, you may use a service locator, when you cannot get hold of certain dependencies. But those cases are rare.
UPDATE :
Implementation of an ICustomerFactory:
public interface ICustomerFactory {
IEnumerable<Customer> CreateCustomers(DataTable data);
}
public class CustomerFactory
{
public IEnumerable<Customer> CreateCustomers(DataTable data)
{
return (from DataRow row in data.Rows
select new Customer
{
Name = row[0].ToString(), Email = row[1].ToString()
}).ToList();
}
}