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 repository is where the data is stored. The service is what manipulates the data. In a real-world situation comparison, if your money is stored in a vault in a bank, the vault is the repository. The teller that deposits, withdraws, etc is the service.
Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database.
According to documentaion @Repository , @Service , @Controller are all synonyms. They all are just specializations of @Component annotation. So, generally, they can be used one instead of other.
@Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With