简体   繁体   中英

Service vs. Repository

Wherein lies the advantage of the first approach getting customer data?

ICustomerService customerService = MyService.GetService<ICustomerService>();
ICustomerList customerList = customerService.GetCustomers();

vs.

ICustomerRepository customerRepo = new CustomerRepository();
ICustomerList customerList = customerRepo.GetCustomers();

If you understand my question you will not ask how the implementation of the MyService class looks like ;-)

here is the implementation of the Repo...

interface ICustomerRepository
{
    ICustomerList GetCustomers();
}

class CustomerRepository : ICustomerRepository
{
    public ICustomerList GetCustomers()
    {...}
}

The advantage of the first approach is that by using a service locator you can easily swap out the implementation of ICustomerService if needed. With the second approach, you would have to replace every reference to the concrete class CustomerRepository in order to switch to a different ICustomerService implementation.

An even better approach is to use a dependency injection tool such as StructureMap or Ninject (there are many others) to manage your dependencies.

Edit: Unfortunately many typical implementations look like this which is why I recommend a DI framework:

public interface IService {}
public interface ICustomerService : IService {}
public class CustomerService : ICustomerService {}
public interface ISupplerService : IService {}
public class SupplierService : ISupplerService {}

public static class MyService
{
    public static T GetService<T>() where T : IService
    {
        object service;
        var t = typeof(T);
        if (t == typeof(ICustomerService))
        {
            service = new CustomerService();
        }
        else if (t == typeof(ISupplerService))
        {
            service = new SupplierService();
        }
        // etc.
        else
        {
            throw new Exception();
        }
        return (T)service;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM