Getting more and more familiar with DI but I still have few niggles.
Read few articles where it says "Injection must be done at the entry point"
Suppose I have a situation where we have wcf Services and these are used both by internal win/web application and external third parties uses those wcf services.
Now where do you inject the Services and repositories?
Above to me seems to be a common scenarios!
Also i pass all those interfaces around.(Very good for mocking) how do I stop somebody from calling EG my repository from a layer that should NOT be calling the repository.
EG only the business Layer should call DAL.
Now by injecting a IRepository into a controller nothing stops a developer from calling the DAL.
Any suggestion? Links that clear all this
Noddy example of my poor man DI. How do I do the same using unity and Injecting all at the entryPoint?
[TestFixture]
public class Class1
{
[Test]
public void GetAll_when_called_is_invoked()
{
var mockRepository = new Mock<ICustomerRepository>();
mockRepository.Setup(x => x.GetAll()).Verifiable();
new CustomerService(mockRepository.Object);
ICustomerBiz customerBiz = new CustomerBizImp(mockRepository.Object);
customerBiz.GetAll();
mockRepository.Verify(x=>x.GetAll(),Times.AtLeastOnce());
}
}
public class CustomerService : ICustomerService //For brevity (in real will be a wcf service)
{
private readonly ICustomerRepository _customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerBizImp : ICustomerBiz
{
private readonly ICustomerRepository _customerRepository;
public CustomerBizImp(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerRepository : ICustomerRepository
{
public IEnumerable<Customer> GetAll()
{
throw new NotImplementedException();
}
}
public interface ICustomerRepository
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerService
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerBiz
{
IEnumerable<Customer> GetAll();
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
thanks
This is a blog post on Composition roots or what you call entry points. Its from Mark Seemann the author of Dependency Injection in .NET. If you are looking for a deep understanding of DI this book is a must read.
There are a lot of samples out there on how to combine WCF and DI. If you are hosting your services in IIS you would need to write a custom ServiceHostFactory where you initialize you DI container. This is a sample for Microsoft's Unity.
As to
how do I stop somebody from calling EG my repository from a layer that should NOT be calling the repository
Do you use poor man's DI and pass all your references around through all your layers? Then you should definitely consider using a DI/IoC container like StructureMap, Castle Windsor, AutoFac or Unity.
If you are asking "how can I in general avoid the situation that someone does not follow my layer boundaries": Write tests that fail if an assembly references another one it should not reference (e.g. UI should not reference DAL).
UPDATE
I assume you wanted the service to use ICustomerBiz instead of the ICustomerRepository. If that is right the setup for Unity would look like this:
[TestMethod]
public void GetAll_with_Unity()
{
var container = new UnityContainer();
container.RegisterType<ICustomerRepository, CustomerRepository>();
container.RegisterType<ICustomerBiz, CustomerBizImp>();
container.RegisterType<ICustomerService, CustomerService>();
var svc = container.Resolve<ICustomerService>();
var all = svc.GetAll();
Assert.AreEqual(1, all.Count());
}
DI is much more about injecting a dependency inside your dipendency architecture, that's why it can not resolve, as is, layers isolation problem you face.
Production code can and should contain DI code, if it needed.
If we are talking about plugin-based architectureDI is one of most natural choices out there.
if we are talking about app behaviour change, like for example Logging system choice: save on remote server if connection present if not injject local logger for future sync with the server.
There are plenty of usages of DI in production, but all that is up to Architect to decide when, how and if use it.
In other words, there is no single rule of it use, it's not a hummer for any nail, so use it where you think it's approriate and use it wisely.
Related
I'm facing a problem trying to implement a unit test for a method on a service.
The architecture of the project is a little bit cumbersome, to say the less...
The problem is that within the method to test it calls another method to take an instance of another service, here is the little monster:
public void SendOrderEmail(string orderCode)
{
Order order= GetOrderService().SerachByCode(orderCode);
.... Send email with the order ....
}
private IOrderService GetOrderService()
{
return OrderService = AutofacDependencyResolver.Current.ApplicationContainer.Resolve<IOrderService>();
}
Please, don't ask why a service calls another service or why is that service not injected at the constructor, as i said the architecture of this project is weird in some points.
I just need to know what is the way to implement a unit test for a method like that.
Thank you!
I would refactor a little the code, let the class that implement this method have IOrderService injected through the constructor, save the instance and then use it,
this way you can inject your fake IOrderService during the test (or use Automock) :)
If you really really can't change the constructor, you can use a property to set IOrderService
---------------- edit
Since i got some downvote on this answer I've tried to get to understand better what is going on.
I'm not sure about this, but seems like you can't edit this class you wrote about, you just want to test it.
Well if that is the case i think i can still give you some advices.
Advice number one: make a test project, link the class file, make a new file with a class like the following one.
class AutofacDependencyResolver {
public static Current { get; private set; }
public ILifetimeScope ApplicationContainer { get; private set; }
public AutofacDependencyResolver(ILifetimeScope scope) {
Current = this;
ApplicationContainer = scope;
}
}
Since the class you need to test is linked it's gonne to compile it and you just can now achieve what you need.
The other (and i think better) advice is do not test stuff you did not wrote / can't modify. What i'm suggesting is writing an adapter, so a class that use the one you can't modify as a black box.
In this case i think you need to test the email, so just check the email output the address stuff like that and ignore the rest.
the people who wrote those classes should have followed solid principles...
As others have said, and you're probably aware yourself anyway, you really want to refactor classes like this and use constructor injection if at all possible. Service location is generally considered an anti-pattern (https://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/) and it specifically makes unit testing like this harder and less transparent.
However, if you absolutely can't refactor, you can still make methods like this somewhat testable by just providing different registrations for the services you're accessing via service location.
In your case, if you have:
public class EmailSender
{
public void SendOrderEmail(string orderCode)
{
Order order = GetOrderService().SearchByCode(orderCode);
//....Send email with the order ....
}
private IOrderService GetOrderService()
{
return AutofacDependencyResolver.Current.ApplicationContainer.Resolve<IOrderService>();
}
}
...and you're looking to specifically run unit tests over SendOrderEmail to validate the logic surrounding your IOrderService implementation (which could be easily covered by a separate test), the other classes implied there might look like:
public class AutofacDependencyResolver // this is problematic but we can't change it
{
public AutofacDependencyResolver(IContainer applicationContainer)
{
ApplicationContainer = applicationContainer;
}
public IContainer ApplicationContainer { get; }
public static AutofacDependencyResolver Current { get; private set; }
public static void SetContainer(IContainer container)
{
Current = new AutofacDependencyResolver(container);
}
}
public static class ContainerProvider // this sets up production config across your app
{
public static IContainer GetProductionContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<RealOrderService>()
.As<IOrderService>();
// register all other real dependencies here
return builder.Build();
}
}
With that setup, you only need to provide mocks which are required for the specific method you're testing, assuming you can set your container within AutofacDependencyResolver easily in order to have production and test configuration running in parallel. That might look like the following, using xUnit, Moq and Autofac in a test project:
public class EmailSenderTests
{
private readonly Mock<IOrderService> _orderService;
public EmailSenderTests()
{
// to set up the test fixture we'll create a mock OrderService and store a reference to the mock itself for validation later on
_orderService = new Mock<IOrderService>();
var mockOrder = new Order();
_orderService.Setup(os => os.SearchByCode(It.IsAny<string>()))
.Returns(mockOrder);
}
private IContainer GetTestContainer()
{
// here we're adding just one registration we need, setting the mocked OrderService instance to be used for IOrderService
var builder = new ContainerBuilder();
builder.Register(c => _orderService.Object)
.As<IOrderService>();
return builder.Build();
}
[Fact]
public void SendEmail()
{
AutofacDependencyResolver.SetContainer(GetTestContainer()); // set the test container on the global singleton
var sender = new EmailSender();
sender.SendOrderEmail("abc"); // internally the email sender will retrieve the mock IOrderService via service location
// make any assertions here, e.g.
_orderService.Verify(os=>os.SearchByCode("abc"), Times.Exactly(1));
}
}
Using Autofac, given multiple interfaces in constructor parameters which is not what I want to achieve, let's say I have;
public class SomeController : ApiController
{
private readonly IDomainService _domainService;
private readonly IService1 _service1;
private readonly IService2 _service2;
private readonly IService3 _service3;
public SomeController(IDomainService domainService,
Iservice1 service1,
IService2 service2,
IService2 service3, ...)
{
_domainService = domainService;
_service1 = service1;
_service2 = service2;
_service3 = service3;
...
}
}
Or, we may do one interface and has multiple properties, e.g.;
public interface IAllServices
{
IDomainService DomainService { get; set; }
IService1 Service1 { get; set; }
IService2 Service2 { get; set; }
IService3 Service3 { get; set; }
}
public class SomeController : ApiController
{
private readonly IAllServices _allServices;
public SomeController(IAllServices allServices)
{
_allServices = allServices;
var domainService1 = _allServices.DomainService;
var service1 = _allServices.Service1;
etc...
}
}
However, I would like to have a list of services, and this code works for me, i.e.;
public interface IMyApp
{
IEnumerable<dynamic> Services { get; set; }
}
public class SomeController : ApiController
{
private readonly IMyApp _myapp;
public SomeController(IMyApp myapp)
{
_myapp = myapp;
foreach (var item in _myapp.Services)
{
if (item is IService1) { // do something... }
if (item is IService2) { // do something... }
if (item is IWhatever) { // do whatever something... }
}
}
}
But, I don't have a better best practice how to create the module, here is my module;
public class MainModule : Autofac.Module
{
private readonly string[] _serviceNames;
private readonly IDomainService _domainService;
public MainModule(IDomainService domainService, params string[] serviceNames)
{
_serviceNames = serviceNames;
_domainService = domainService;
}
protected override void Load(ContainerBuilder builder)
{
List<dynamic> _services = new List<dynamic>();
_services.Add(_domainService);
foreach (var serviceName in _serviceNames)
{
switch (serviceName)
{
case "MyService1":
IService1 service1 = new Service1();
_modules.Add(service1);
break;
case "MyService2":
IService2 service2 = new Service2();
_modules.Add(service2);
break;
case "SomeWhateverService":
IWhatever whateverService = new WhateverService();
_modules.Add(whateverService);
break;
}
}
builder.RegisterType<MyApp>()
.As<IMyApp>()
.WithParameter(new TypedParameter(typeof(IEnumerable<dynamic>), _services));
}
}
So, this code works, but I would like to make my DomainService and all of the Services registered in the container as well. That is, I want to replace whatever inside the switch statement without new keyword.
IService1 service1 = new Service1();
_modules.Add(service1);
And I would like to register the domain service as well. So, inside my Bootstrapper is like this;
public static class Initializer
{
public static IContainer BuildContainer(
HttpConfiguration config, Assembly assembly, IDomainService domainService, params string[] services)
{
var builder = new ContainerBuilder();
builder.RegisterApiControllers(assembly);
builder.RegisterWebApiFilterProvider(config);
builder.RegisterModule(new MainModule(domainService, services));
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
return container;
}
}
And what happen is, I need to create the domain service in the startup, i.e.;
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
MyDomainService domainService = new MyDomainService();
var container =
Initializer.BuildContainer(
GlobalConfiguration.Configuration,
Assembly.GetExecutingAssembly(),
domainService,
"MyService1", "MyService2", "SomeWhateverService");
}
}
You can see that I have to create the domain service first, which is not using IoC;
MyDomainService domainService = new MyDomainService();
and add to the module.
The big question, how to do this in proper way using Autofac. My Bootstrapper is in another project and all of the interfaces are in other project as well.
Many thanks for the help. And sorry for the long question.
Solution:
After testing several model, it seems the best way is to use domain events model for this type of scenario instead of injecting the services into the domain.
The proper way of doing dependency injection is using Constructor Injection. Constructor Injection should always your preferred choice, and only under high exception, you should fall back to another method.
You proposed property injection as an alternative, but this causes Temporal Coupling which means that classes can be initialized while a required dependency is missing, causing null reference exceptions later on.
The method where you inject a collection containing all services where the constructor is responsible of getting the dependencies it needs, is a variation of the Service Locator pattern. This pattern is littered with problems and is considered to be an anti-pattern.
Grouping dependencies into a new class and injecting that is only useful in case that class encapsulates logic and hides the dependencies. This pattern is called Facade Service. Having one big service that exposes the dependencies for others to use can be considered a form of the Service Locator anti-pattern, especially when the number of services that this class exposes starts to grow. It will become the common go-to object for getting services. Once that happens, it exhibits the same downsides as the other form of Service Locator does.
Extracting dependencies into a different class while allowing the consumer to use those dependencies directly doesn't help in reducing complexity of the consumer. That consumer will keep the same amount of logic and the same number of dependencies.
The core problem here seems that your classes get too many dependencies. The great thing about constructor injection though is that it makes it very clear when classes have too many dependencies. Seeking other methods to get dependencies doesn't make the class less complex. Instead of trying other methods of injection, try the following:
Apply the Single Responsibility Principle. Classes should have one reason to change.
Try extracting logic with its dependencies out of the class into a Facade Service
Remove logic and dependencies that deals with cross-cutting concerns (such as logging and security checks) from the class and place them in infrastructure (such as decorators, interceptors or depending on your framework into handlers, middleware, message pipeline, etc).
After testing several model, it seems the best way is just use domain events pattern for this type of scenario instead of injecting the services into the domain.
I refer to Udi Dahan article on domain events:
http://udidahan.com/2009/06/14/domain-events-salvation/
I have a question about the best way to design classes in order to be test-friendly. Suppose I have an OrderService class, which is used to place new orders, check the status of orders, and so on. The class will need to access customer information, inventory information, shipping information, etc. So the OrderService class will need to use CustomerService, InventoryService, and ShippingService. Each service also has its own backing repository.
What is the best way to design the OrderService class to be easily testable? The two commonly used patterns that I've seen are dependency injection and service locator. For dependency injection, I'd do something like this:
class OrderService
{
private ICustomerService CustomerService { get; set; }
private IInventoryService InventoryService { get; set; }
private IShippingService ShippingService { get; set; }
private IOrderRepository Repository { get; set; }
// Normal constructor
public OrderService()
{
this.CustomerService = new CustomerService();
this.InventoryService = new InventoryService();
this.ShippingService = new ShippingService();
this.Repository = new OrderRepository();
}
// Constructor used for testing
public OrderService(
ICustomerService customerService,
IInventoryService inventoryService,
IShippingService shippingService,
IOrderRepository repository)
{
this.CustomerService = customerService;
this.InventoryService = inventoryService;
this.ShippingService = shippingService;
this.Repository = repository;
}
}
// Within my unit test
[TestMethod]
public void TestSomething()
{
OrderService orderService = new OrderService(
new FakeCustomerService(),
new FakeInventoryService(),
new FakeShippingService(),
new FakeOrderRepository());
}
The disadvantage to this is that every time I create an OrderService object that I'm using in a test, it takes a lot of code to call the constructor within my tests. My Service classes also end up with a bunch of properties for each Service and Repository class that they use. And as I expand my program and add more dependencies between various Service and Repository classes, I have to go back and add more and more parameters to constructors of classes that I've already made.
For a service locator pattern, I could do something like this:
class OrderService
{
private CustomerService CustomerService { get; set; }
private InventoryService InventoryService { get; set; }
private ShippingService ShippingService { get; set; }
private OrderRepository Repository { get; set; }
// Normal constructor
public OrderService()
{
ServiceLocator serviceLocator = new ServiceLocator();
this.CustomerService = serviceLocator.CreateCustomerService()
this.InventoryService = serviceLocator.CreateInventoryService();
this.ShippingService = serviceLocator.CreateShippingService();
this.Repository = serviceLocator.CreateOrderRepository();
}
// Constructor used for testing
public OrderService(IServiceLocator serviceLocator)
{
this.CustomerService = serviceLocator.CreateCustomerService()
this.InventoryService = serviceLocator.CreateInventoryService();
this.ShippingService = serviceLocator.CreateShippingService();
this.Repository = serviceLocator.CreateOrderRepository();
}
}
// Within a unit test
[TestMethod]
public void TestSomething()
{
OrderService orderService = new OrderService(new TestServiceLocator());
}
I like how the service locator pattern results in less code when calling the constructors, but it also gives less flexibility.
What's the recommended way to set up my Service classes that have dependencies on several other Services and Repositories so that they can be easily tested? Are either or both of the ways that I showed above good, or is there a better way?
Just a really quick answer to put you on the right track.
In my experience, if you aim for easily testable code you tend to end up with clean maintainable code as a nice side-effect. :-)
Some key points to remember:
The SOLID principles will really help you create good, clean, testable code.
(S + O + I) Break this Service up into smaller services that only do one thing, and will therefore only have one reason to change. At a minimum placing an order and checking the status of an order are completely different things. If you think quite deeply about it, you don't really need to follow the most obvious steps (eg. check credit->check stock->check shipping), some of these can be done out of order - but that's a whole other story that would probably require a different business model. Anyway you can use the Facade pattern to create a simplified view on top of those smaller services if you really need it.
Use an IoC container (eg unity)
Use a Mocking framework (eg Moq)
The service locator pattern is actually considered an anti-pattern/code smell - so please don't use it.
Your tests should use the same paths as you real code, so get rid of the 'Normal constructor'. The 'Constructor used for testing' in your first example is what your constructor should look like.
Do NOT instantiate the required services inside your class - they should be passed in instead, as an Interface. The IoC container will help you deal with this part. By doing this you are following the D in Solid (Dependency inversion principle)
Avoid using/referencing static classes/methods directly inside your own classes as much as possible. Here I'm talking about using things like DateTime.Now() directly, instead of wrapping them in an interface/class first.
For example here you could have a IClock interface with a GetLocalTime() method that your classes can use instead of using the system functions directly. This allows you to inject a SystemClock class at run-time and a MockClock during testing. By doing this you can gain full control of exactly what time is returned to your system/class under test. This principle obviously applies to all other static references that could return unpredictable results. I know it adds yet another thing you need to pass into your classes, but it at least makes that pre-existing dependency explicit and prevents the goal posts from continuously moving during testing (without having to resort to black magic, like MS Fakes).
This is a minor point, but your private properties here should really be fields
There is a difference between code that is "testable" and code that is loosely coupled.
The primary purpose of using DI is loose coupling. Testability is a side-benefit that is gained from loosely coupled code. But code that is testable isn't necessarily loosely coupled.
While injecting a service locator is obviously more loosely coupled than having a static reference to one, it is still not a best practice. The biggest drawback is lack of transparency of dependencies. You might save a few lines of code now by implementing a service locator and then think you are winning, but whatever is gained by doing so is lost when you actually have to compose your application. There is a distinct advantage to looking at the constructor in intellisense to determine what dependencies a class has then to locating the source code for that class to try to work out what dependencies it has.
So, as you might have guessed, I am recommending you use constructor injection. However, you also have an anti-pattern known as bastard injection in your example. The primary drawback of bastard injection is that you are tightly coupling your classes on each other by newing them up internally. This may seem innocent, but what would happen if you needed to move your services into separate libraries? There is a good chance that would cause circular dependencies in your application.
The best way to deal with this (especially when you are dealing with services and not configuration settings) is to either use pure DI or a DI container and just have a single constructor. You should also use a guard clause to ensure there is no way to create your order service without any dependencies.
class OrderService
{
private readonly ICustomerService customerService;
private readonly IInventoryService inventoryService;
private readonly IShippingService shippingService;
private readonly IOrderRepository repository;
// Constructor used for injection (the one and only)
public OrderService(
ICustomerService customerService,
IInventoryService inventoryService,
IShippingService shippingService,
IOrderRepository repository)
{
if (customerService == null)
throw new ArgumentNullException("customerService");
if (inventoryService == null)
throw new ArgumentNullException("inventoryService");
if (shippingService == null)
throw new ArgumentNullException("shippingService");
if (repository == null)
throw new ArgumentNullException("repository");
this.customerService = customerService;
this.inventoryService = inventoryService;
this.shippingService = shippingService;
this.repository = repository;
}
}
// Within your unit test
[TestMethod]
public void TestSomething()
{
OrderService orderService = new OrderService(
new FakeCustomerService(),
new FakeInventoryService(),
new FakeShippingService(),
new FakeOrderRepository());
}
// Within your application (pure DI)
public class OrderServiceContainer
{
public OrderServiceContainer()
{
// NOTE: These classes may have dependencies which you need to set here.
this.customerService = new CustomerService();
this.inventoryService = new InventoryService();
this.shippingService = new ShippingService();
this.orderRepository = new OrderRepository();
}
private readonly IOrderService orderService;
private readonly ICustomerService customerService;
private readonly IInventoryServcie inventoryService;
private readonly IShippingService shippingService;
private readonly IOrderRepository orderRepository;
public ResolveOrderService()
{
return new OrderService(
this.customerService,
this.inventoryService,
this.shippingService,
this.orderRepository);
}
}
// In your application's composition root, resolve the object graph
var orderService = new OrderServiceContainer().ResolveOrderService();
I also agree with Gordon's answer. If you have 4 service dependencies it is a code smell that your class is taking on too many responsibilities. You should consider refactoring to aggregate services to make your classes singular in responsibility. Of course, 4 dependencies is sometimes necessary, but it is always worth taking a step back to see if there is a domain concept that should be another explicit service.
NOTE: I am not necessarily saying that Pure DI is the best approach, but it can work for some small applications. When an application becomes complex, using a DI container can pay dividends by using convention-based configuration.
I'm creating a class library API that wraps business logic and access to an SQL Server database via Entity Framework 6.
I've designed it using the Unit of work and repository patterns.
The purpose is to make it easy to use and to unit test.
Business logic and validation will be performed in the service layer.
I will not use an IOC container because I feel that it would complicate the API
usage.
The project have 15 repositories and services
The current design is as follows:
Service Layer A -> Unit of work -> Repository A and or B
Service Layer B -> Unit of work -> Repository B and or A...
...
public class ServiceA : IServiceA, IService
{
private readonly IUnitOfWork unitOfWork;
public AssetService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
...
public IList<DomainObjectA> GetAll()
{
return unitOfWork.RepositoryA.GetAll();
}
public void Dispose()
{
unitOfWork.Dispose();
}
...
}
public class UnitOfWork : IUnitOfWork
{
private readonly MyDbContext context = new MyDbContext();
private IRepositoryA repositoryA;
private IRepositoryB repositoryB;
...
public IRepositoryA RepositoryA
{
get { return repositoryA = repositoryA ?? new RepositoryA(context); }
}
public IRepositoryB RepositoryB
{
get { return repositoryB = repositoryB ?? new RepositoryB(context); }
}
...
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class RepositoryA : Repository, IRepositoryA
{
public RepositoryA(MyDbContext context)
: base(context) {}
public IList<DomainObjectA> GetAll()
{
return context.tblA.ToList().Select(x => x.ToDomainObject()).ToList();
}
...
}
Since this is an API that should be used by other projects, I need a nice and "fairly" easy to use interface for the user that consumes the API.
Because of this the UnitOfWork is created in this "public interface" between the user and the service layer, see below.
I also think it's best that the using-statement lies within the API so that the db-context is disposed properly and immediately after each service call.
I started out using the Proxy pattern for this:
Example:
public class ProxyA : Proxy, IServiceA
{
public IList<DomainObjectA> GetAll()
{
using (var service = GetService<ServiceA>())
return service.GetAll();
}
...
}
public abstract class Proxy
{
protected T GetService<T>() where T : IService
{
return (T)Activator.CreateInstance(typeof(T), new object[] { new UnitOfWork()});
}
}
But this would require me to create a proxy for each service. I could of course skip the service interface in the proxy and create a common proxy which handles all the services.
I've also looked at the Facade pattern but can't decide which pattern to use for this particular scenario.
My questions:
Is this a good approach or are there any other design patterns that will solve this problem?
Also, should there be one public API entry point or several, grouped by some business logic?
I see nothing wrong with your design and the patterns you use.
Regarding the proxy pattern it is your call if you want to use it or not. As you mention you have to create boiler plate code to create one for every service. If it is arguable if you want to use it only to hide the call to the db service, or you prefer to add that line of code every time you call the service (and make sure you do it to avoid leaks). Also you may consider if you may need to add extra functionality in the Proxy in the future, which will put extra weight to create the proxy option.
Regarding a single entry point or several, I would create a ServiceA, ServiceB, ServiceC etc (so several) grouped for business logic domains. Typically you'll have between 5-20 (just an approximate number to give an idea of the magnitude)
You may want to review the interface segregation principle which supports this idea
http://en.wikipedia.org/wiki/Interface_segregation_principle
I have read from internet I got this points which says Interfaces is used for this
Use TDD methods
Replace persistance engine
But I'm not able to understand how interface will be usefull to this point Replace persistance engine.
lets consider I'm creating a basic(without generics) repository for EmployeeRepository
public class EmployeeRepository
{
public employee[] GetAll()
{
//here I'll return from dbContext or ObjectContex class
}
}
So how interfaces come into picture?
and if suppose i created an interface why upcasting is used ? for e.g
IEmployee emp = new EmployeeRepository() ;
vs
EmployeeRepository emp = new EmployeeRepository();
Please explain me precisely and also other usefullness of Interface in regard to Repository Pattern.
So how interfaces come into picture ?
Like this:
public interface IEmployeeRepository
{
Employee[] GetAll();
}
and then you could have as many implementations as you like:
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
and so on ... you could have as many implementation as you like
As you can see it's not really important how we implement the repository. What's important is that all repositories and implementations respect the defined contract (interface) and all posses a GetAll method returning a list of employees.
And then you will have a controller which uses this interface.
public class EmployeesController: Controller
{
private readonly IEmployeeRepository _repository;
public EmployeesController(IEmployeeRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
var employees = _repository.GetAll();
return View(employees);
}
}
See how the controller no longer depends on a specific implementation of the repository? All it needs to know is that this implementation respects the contract. Now all that you need to do is to configure your favorite dependency injection framework to use the implementation you wish.
Here's an example of how this is done with Ninject:
Install the Ninject.MVC3 NuGet
In the generated ~/App_Start/NinjectWebCommon.cs code you simply decide to use the EF implementation with a single line of code:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IEmployeeRepository>().To<EmployeeRepositoryEF>();
}
This way you no longer need to do any manual instantiations of those repository classes and worry about upcasting or whatever. It is the dependency injection framework that manages them for you and will take care of injecting the defined implementation into the controller constructor.
And by simply modifying this configuration you could switch your data access technology without touching a single line of code in your controller. That's way unit testing in isolation also comes into play. Since your controller code is now weakly coupled to the repository (thanks to the interface we introduced) all you need to do in the unit test is to provide some mock implementation on the repository which allows you to define its behavior. This gives you the possibility to unit test the Index controller action without any dependency on a database or whatever. Complete isolation.
I also invite you to checkout the following articles about TDD and DI in ASP.NET MVC.
You would expose your repository as an interface:
public interface IEmployeeRepository
{
List<Employee> GetAll();
}
This would allow you to have many different implementations of the interface, such as the default one:
public class EmployeeRepository : IEmployeeRepository
{
public List<Employee> GetAll()
{
// Return from db.
}
}
Or a test one:
public class TestEmployeeRepository : IEmployeeRepository
{
public List<Employee> GetAll()
{
// Stub some dummy data.
}
}
Your code consuming the repository is then only interested in using the interface:
IEmployeeRepository myRepo = MyRepositoryFactory.Get<IEmployeeRepository>();
The secret sauce is the factory, or another mechanism by which to resolve the interface into a usable type (a Dependency Injection framework such as Ninject, or Castle Windsor will fulfil this role).
The point is, the consuming code doesn't care about the implementation, only the contract (the interface). This allows you to swap out implementations for testing purposes very easily and promotes loose coupling.
Just to clarify, there is no link between the use of interfaces and the repository pattern specifically, it is just another pattern that can make use of them.