I have a bank account domain as listed below. There can be SavingsAccount, LoanAccount, FixedAccount and so on. One user can have multiple accounts. I need to add a new functionality – get all accounts for a user. Where should be the function written and how?
It would be great if the solution follows SOLID principles( Open-Closed principle,…) and DDD.
Any refactoring that would make the code better is welcome.
Note: The AccountManipulator will be used by a website client over a web service.
namespace BankAccountBL
{
public class AccountManipulator
{
//Whether it should beprivate or public?
private IAccount acc;
public AccountManipulator(int accountNumber)
{
acc = AccountFactory.GetAccount(accountNumber);
}
public void FreezeAccount()
{
acc.Freeze();
}
}
public interface IAccount
{
void Freeze();
}
public class AccountFactory
{
public static IAccount GetAccount(int accountNumber)
{
return new SavingsAccount(accountNumber);
}
}
public class SavingsAccount : IAccount
{
public SavingsAccount(int accountNumber)
{
}
public void Freeze()
{
}
}
}
READING:
When to use the CQRS design pattern?
In domain-driven design, would it be a violation of DDD to put calls to other objects' repostiories in a domain object?
Refactoring domain logic that accesses repositories in a legacy system
Which of these examples represent correct use of DDD?
Good Domain Driven Design samples
Advantage of creating a generic repository vs. specific repository for each object?
if your AccountManipulator is a Façade to your domain, I wouldn't put the account number in the constructor. I would refactor it this way:
public class AccountManipulator
{
private AccountFactory _factory;
private UserRepository _users;
public AccountManipulator(AccountFactory factory, UserRepository users)
{
_factory = factory;
_users = users;
}
public void FreezeAccount(int accountNumber)
{
var acc = _factory.GetAccount(accountNumber);
acc.Freeze();
}
public IEnumerable<IAccount> GetAccountsOf(User user) {
return _users.GetAccountIds(user).Select(_factory.GetAccount);
}
}
public interface UserRepository {
IEnumerable<int> GetAccountIds(User user);
}
In order to state if your domain is SOLID, you should analyze it with the principle:
Single Responsibility: every object has is own responsibility (and only that one):
AccountFactory: creates IAccounts
SavingsAccount: implementation of IAccount that reads from/writes to (a database? a web service?)
AccountManipulator: provide a minimal and simple set of operations to do with domain objects.
Open/Closed: are you classes are open to extensions and closed to changes?
AccountFactory: well, no. If you write a new implementation of IAccount, in order to use it you have to change AccountFactory. Solution: abstract factory
SavingsAccount? It depends if it will use external dependencies. Need more code to say.
AccountManipulator: yes. If you need to do another operation with your domain objects, you can use directly the other services without change AccountManipulator. Or you can inherit from it
Liskov substitution: can you substitute any class with another implementation? Need more code to say. You have no other implementations of IAccount or IAccountFactory now
Dependency Inversion:
AccountManipulator should depend on abstractions: AccountFactory and UserRepository should be interfaces.
Firstly, to really answer your question it's important to know why you need to get all user accounts? Are you:
Fetching a list of accounts to display on screen for the user to
then perform a command/transaction against a single account?
Performing a single command/transaction on all of the users accounts - such as 'Freeze All User Accounts'?
The reason I ask is because you only need to consider the DDD aspect if it's the latter. If the reason for this 'functionality' is the former (and after reading your question I suspect it is) - I really recommend just creating a thin query service layer that gets the user's account data you need for the screen. You don't need to add the 'restrictions' of DDD for this; there are no transactions or model state changes involved. Providing this functionality doesn't have to involve the domain model at all. Just define some simple POCO DTO's and use Entity Framework to get the data and pass it back to the UI.
This is what CQRS is about; you don't need repositories, factories or aggregates to give the UI a list of accounts for the user to choose from - you would be over complicating it and making A LOT more work for yourself.
If there is a scenario that requires a single transaction over all of the user's accounts then I'd do something like:
public class AccountService : IAccountService
{
private IAccountRepository _accountRespository;
public void FreezeAllAccountsForUser(Guid userId)
{
IEnumerable<IAccount> accounts = _accountRespository.GetAccountsByUserId(userId);
using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
{
foreach (IAccount account in _accounts)
{
account.Freeze();
_accountRespository.Save(account);
}
}
}
}
Where AccountService is a webservice, i.e. the Application Layer.
In summary, my advice is: Only consider DDD in the context of commands that require transactions. For fetching lists of data; create a simple query service that the UI can consume.
P.S. I've noticed the misuse of the Factory pattern in your question and some of the answers. Factories are designed to provide an object's CREATION strategy, given particular data. There shouldn't be a 'GetAccount(accountId)' method that calls the database; repositories call the database then pass data to a factory to create the object.
First of all why do you need AccountManipulator? It does absolutely nothing, but makes the code more complicated.
As for getting all accounts of a User, the most logical place to put this method would be in the User class. You could pass an account factory to that method, further implementation would probably depend on how you store accounts.
I'd rename 'AccountFactory' to AccountRepository and put an extra method in it GetAccountsForUser( int userId ) which retrieves all Accounts for a specific user.
If AccountManipulator is a webservice, then this class will use the AccountRepository, like this:
public class AccountManipulator
{
public void FreezeAccount( int accountNr )
{
var repository = new AccountRepository();
var account = repository.GetAccount(accountNr);
account.Freeze();
repository.Save(account);
}
public ICollection<Account> GetAccountsForUser( int userId )
{
var repository = new AccountRepository();
return repository.GetAccountsForUser (userId);
}
}
Related
I'm making an application that uses an external API. But I don't want my application to be dependant on the API. So I have been reading about how to achieve this. I read that the thing I want is loose coupling. I want to loosely couple my class that uses the external API from the rest of my application. My question is how do I achieve this. If read about different design patterns, I can't find one that helps with my problem.
public class GoogleCalendarService
{
private const string CalendarId = ".....";
private CalendarService Authenticate(string calendarId)
{
...
}
public void Create(Booking newBooking, string userId)
{
...
InsertEvent(newEvent, userId);
}
private void Insert(Event newEvent, string userId)
{
call authenticate account
....
}
public List<Booking> GetEvents()
{
call authenticate account
...
}
}
Above is my code for the class that uses the external API. In the rest of my application I use this class the following way:
public class MyApplication
{
private void MyFunction()
{
GoogleCalendarService googleCalendarService = new GoogleCalendarService();
googleCalendarService.CreateEvent(..., ...)
}
}
I do this on multiple places in my application. So my question is: How can I loosely couple the API class from the rest?
Edit: I probably want a general calendar service interface that makes it easier to replace the google calendar service with an other calendar service when needed.
that makes it easier to replace the google calendar service with an other calendar service
The main pattern you will want to look at is Adapter. But you would want to use that in combination with Dependency Injection.
The DI first:
public class MyApplication
{
// constructor injection
private IGeneralCalendarService _calendarService;
public MyApplication(IGeneralCalendarService calendarService)
{
_calendarService = calendarService;
}
private void MyFunction()
{
_calendarService.CreateEvent(..., ...)
}
}
And the Adapter would look something like
public class GoogleCalendarServiceAdapter : IGeneralCalendarService
{
// implement the interface by calliong the Google API.
}
In addition you will need generic classes for Event etc. They belong to the same layer as the interface.
You need to write a wrapper around that API. And rewrite every Output/Input of that API with your wrapper IO. And after that, you can take advantage of Dependancy Injection to use your own code. By this way you can have an abstraction layer around that API
Will be thankful for your attention, time and efforts !
I have the following code
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Role { get; set; }
}
public interface IEmployeeRepository
{
Employee GetEmployee(string firstName, string role);
}
public class EmployeeRepository : IEmployeeRepository
{
public Employee GetEmployee(string firstName, string role)
{
//logic here
return new Employee();
}
}
Now i want to implement cache for EmployeeRepository.
At first i did it using Proxy design pattern
public class ProxyEmployeeRepository : IEmployeeRepository
{
private EmployeeRepository _employeeRepository = new EmployeeRepository();
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
//...
}
}
But when wanted to write unit tests for this class i couldn't do it(i cannot create mock for _employeeRepository and verify whether it was called or not)
If i implement cache with Decorator pattern then i would have the following code
public class DecoratorEmployeeRepository : IEmployeeRepository
{
private IEmployeeRepository _employeeRepository;
public DecoratorEmployeeRepository(IEmployeeRepository repository)
{
_employeeRepository = repository;
}
private MemoryCache _cache = new MemoryCache("UsualCache");
public Employee GetEmployee(string firstName, string role)
{
//do not cache administrators
if (role == "admin")
{
return _employeeRepository.GetEmployee(firstName, role);
}
else
{
//get from cache at first
//if absent call _employeeRepository.GetEmployee and add to cache
return null;
}
}
}
and unit tests for it
[TestClass]
public class EmployeeRepositoryTests
{
[TestMethod]
public void GetEmployeeTest_AdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "admin");
innerMock.Received().GetEmployee(Arg.Any<string>(), Arg.Any<string>());
}
[TestMethod]
public void GetEmployeeTest_NotAdminRole()
{
var innerMock = Substitute.For<IEmployeeRepository>();
var employeeRepository = new DecoratorEmployeeRepository(innerMock);
employeeRepository.GetEmployee("Ihor", "NotAdmin");
innerMock.DidNotReceive().GetEmployee("Ihor", "NotAdmin");
}
}
Is it possible to write unit tests for first approach with proxy pattern ? i just don't understand how it is possible to cover proxy class with unit tests ...
I know it is too late to answer your question but it might help other new visitors:
I think your problem is your misunderstanding of both patterns. By using composition instead of instantiating your class inside the proxy, does not necessarily mean that you have changed your pattern from proxy to decorator. Each of these patterns is solving a specific problem. Let me clarify each:
Decorator Pattern:
This pattern is useful when you have different kinds of behaviours in your main class (like caching, logging, lazy loading and etc.) and you want to use each of these or a combination of them in different places of your application. For example, in your controller, you need only caching, in the admin controller you don't need caching but logging and in another service, you need both plus lazy loading. Therefore you will create three decorators for each extra behaviour (caching, logging and lazy loading) and in each place, you link the decorators into each other to provide various kinds of behaviours. The benefit of this pattern is that each class has only one responsibility. Additionally, your application is open to extension and close to modification. If you need a new behaviour, you can simply implement a new decorator from the interface and add it only to the services or controllers that the new behaviour is required without modifying the current implementation.
Proxy Pattern:
This pattern is useful when you want to add specific behaviour or behaviours that are required for your class but can prevent the actual behaviour (querying the database) and/or new behaviours come into the picture (which is not the behaviour in the decorator pattern. It only enhances the main behaviour). Another usage of this pattern is when instantiating the main class is costly. So in contrast, you do not need each behaviour (or various combination of them) separately in several places of your application.
The benefit of this pattern is that it prevents adding several responsibilities to your main class. Besides, it is still close to modification and open to extension. If the requirements change in future, you can simply implement a new proxy and replace it with the correct one or use it separately.
The answer to your question:
Therefore, as I mentioned above, by having a composition to your interface instead of instantiating it directly, you are not changing the pattern. In proxy pattern, the main class can be injected via the interface or the concrete implementation as well.
I have a scenario using WebApi, Generic Repository, EF6 and unit of work pattern
(in order to wrap all changes from several calls to the same context.)
Manager layer is used to perform calls to different repositories and also to other managers.
Currently Customer Manager does inject both repos and other Managers like:
public class CustomerManager {
public CustomerManager(IRepository<Customer> _customerRepository, IRepository<Order> orderRepository, IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public bool Save(Customer customer) {
_orderReporsitory.Find...
_itemManager.IsItemUnique(ItemId)
_customerRepository.Save(customer);
}
}
This code does not compile, for reference only.
Approaches like this
http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/
Will wrap several repositories under a unit of work and flush the changes all together.
My issue involves also adding another Manager layer, to be wrapped also inside unit of work and allow both calls to repositories and other managers
(as I want to reuse some manager logic. Like in the example, I am re-using some ItemManager logic)
This code https://stackoverflow.com/a/15527444/310107
using (var uow = new UnitOfWork<CompanyContext>())
{
var catService = new Services.CategoryService(uow);
var custService = new Services.CustomerService(uow);
var cat = new Model.Category { Name = catName };
catService.Add(dep);
custService.Add(new Model.Customer { Name = custName, Category = cat });
uow.Save();
}
is using something similar of what I need but I would also like to be able to inject the services to unit test them (and not creating instances in the body of my manager/service method)
What would the best approach to do this ?
Thanks
Your code snippet with the unit of work has several problems, such as:
You create and dispose the unit of work explicitly within that method, forcing you to pass along that unit of work from method to method and class to class.
This causes you to violate the Dependency Inversion Principle, because you now depend on concrete types (CategoryService and CustomerService), which complicates your code and makes your code harder to test.
If you need to change the way the unit of work is created, managed or disposed, you will have to make sweeping changes throughout the application; A violation of the Open/Closed Principle.
I expressed these problems in more details in this answer.
Instead, I propose to have one DbContext, share it through a complete request, and control its lifetime in the application's infrastructure, instead of explicitly throughout the code base.
A very effective way of doing this is by placing your service layer behind a generic abstaction. Although the name of this abstraction is irrelevant, I usually call this abstraction 'command handler:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
There are a few interesting things about this abstaction:
The abstraction describes one service operation or use case.
Any arguments the operation might have are wrapped in a single message (the command).
Each operation gets its own unique command class.
Your CustomerManager for instance, might look as follows:
[Permission(Permissions.ManageCustomerDetails)]
public class UpdateCustomerDetailsCommand {
public Guid CustomerId { get; set; }
[Required] public string FirstName { get; set; }
[Required] public string LastName { get; set; }
[ValidBirthDate] public DateTime DateOfBirth { get; set; }
}
public class UpdateCustomerDetailsCommandHandler
: ICommandHandler<UpdateCustomerDetailsCommand> {
public UpdateCustomerDetailsCommandHandler(
IRepository<Customer> _customerRepository,
IRepository<Order> orderRepository,
IManager itemManager) {
_orderReporsitory = orderReporsitory;
_itemManager = itemManager;
_customerRepository = customerRepository;
}
public void Handle(UpdateCustomerDetailsCommand command) {
var customer = _customerRepository.GetById(command.CustomerId);
customer.FirstName = command.FirstName;
customer.LastName = command.LastName;
customer.DateOfBirth = command.DateOfBirth;
}
}
This might look like just a bunch of extra code, but having this message and this generic abstraction allows us to easily apply cross-cutting concerns, such as handling the unit of work for instance:
public class CommitUnitOfWorkCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> {
private readonly IUnitOfWork unitOfWork;
private readonly ICommandHandler<TCommand> decoratee;
public CommitUnitOfWorkCommandHandlerDecorator(
IUnitOfWork unitOfWork,
ICommandHandler<TCommand> decoratee) {
this.unitOfWork = unitOfWork;
this.decoratee = decoratee;
}
public void Handle(TCommand command) {
this.decoratee.Handle(command);
this.unitOfWork.SaveChanges();
}
}
The class above is a decorator: It both implements ICommandHandler<TCommand> and it wraps ICommandHandler<TCommand>. This allows you to wrap an instance of this decorator around each command handler implementation and allow the system to transparently save the changes made in the unit of work, without any piece of code having to do this explicitly.
It is also possible to create a new unit of work here, but the easiest thing to start with is to let the unit of work live for the duration of the (web) request.
This decorator will however just be the beginning of what you can do with decorators. For instance, it will be trivial to:
Apply security checks
Do user input validation
Run the operation in a transaction
Apply a deadlock retry mechanism.
Prevent reposts by doing deduplication.
Register each operation in an audit trail.
Store commands for queuing or background processing.
More information can be found in the articles, here, here and here.
I have created a generic repository for my entity types which handles retrieving , adding and deleting data. Each entity type has a corresponding Service class which interacts with the generic repository to handle all the Data access.
However many times i need to retrieve data based on more than one service and i am never sure where to place this code. For example below is some code that returns a list of email addresses ("GetEmailTrackingAddressGroup" function) which is using 3 different service. I have placed this in the "GroupService" but it could also easily go in the "UserService" aswell.
public class GroupService
{
IRepository<Group> groupRepository;
public GroupService(IRepository<Group> groupRepository)
{
this.groupRepository = groupRepository;
}
public Group GetById(int id)
{
return groupRepository.GetSingle(g => g.Id == id);
}
public static List<string> GetEmailTrackingAddressesGroup(int instanceId, int groupId)
{
MyEntities entityContext = new MyEntities();
UserGroupService userGroupService =
new UserGroupService(new BaseRepoistory<UserGroup>(entityContext ));
UserService userService =
new UserService(new BaseRepoistory<User>(entityContext ));
List<string> emails = new List<string>();
Group productGroup = GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(userService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
My Question is, should you just try and pick the most relevant service and place the code in there and call the other relevant service inside it, or should i create a new class which handles Data access when more than 1 service is involved. For example i have placed code for what this class might look like below.
public class DataFunctions
{
public static List<string> GetEmailTrackingAddressesGroup(int instanceId, int groupId)
{
MyEntities entityContext = new MyEntities();
GroupService userGroupService =
new GroupService(new BaseRepoistory<Group>(entityContext ));
UserGroupService userGroupService =
new UserGroupService(new BaseRepoistory<UserGroup>(entityContext ));
UserService userService =
new UserService(new BaseRepoistory<User>(entityContext ));
List<string> emails = new List<string>();
Group productGroup = GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(userService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
The second approach seems to make more sense as this means each service will never rely on other services however im not sure if i am going about this the right way. One concern i have about using this separate class is that it will get very big and hard to manage.
Edit - For now i have come up with a third solution, i think it is better than my previous two however i'm still uncertain if i am managing this correctly. I have created a seperate "EmailService" which will handle all data queries which are needed when handing email functionality in my main ASP.Net web project.
Below is the code for this new class
//Functionality realting to data needed when handling emails
public class EmailService
{
MyEntities entityContext;
AspUserService aspUserService;
GroupService groupService;
UserGroupService userGroupService;
public EmailService()
{
entityContext = new MyEntities ();
aspUserService = new AspUserService(new RepositoryBase<aspnet_Users>(entityContext));
groupService = new GroupService(new RepositoryBase<Group>(entityContext));
userGroupService = new UserGroupService(new RepositoryBase<UserGroup>(entityContext));
}
public List<string> GetEmailsForProductGroup(int groupId)
{
List<string> emails = new List<string>();
Group productGroup = groupService.GetById(groupId);
foreach (UserGroup userGroup in userGroupService.GetByGroupId(productGroup.Id))
{
if (userGroup.EmailTracking)
emails.Add(aspUserService.GetByUserId(userGroup.UserId).UserName);
}
return emails;
}
}
If you were to do maintenance on an application you've never seen before, where would you expect it to be? Since it is something that "belongs" to a group, i think that putting it in the group-repo/service would be the right approach. In your example, i would suggest creating a new group-repository, extending the IRepository of group, and create a method for getting the group object, including the connection entities. When scaling your application, this will make a huge difference, since you wont have to query the database for every subobject (n+1 problem).
No offense, but all your approaches suck for the following reasons: tight coupling and messing around responsibilities.
The generic repository is an anti pattern, stay away from it. Your first approach pretty much does the work of a repository and it's a static function (why?!).
The services shouldn't be coupled to concrete repositories. All dependencies should be injected as abstractions via constructor. I get the feeling that aspUsersService,GroupService and UserGroupService (what's the difference????) are actually implemented like a repository and thus, they are useless.
Actually from what I see, all your services are practically repositories. Cut the useless code, have one service/repository that uses directly EF and that's it.
It looks like you're a little confused between the point of repositories and service classes. Your service classes are just repositories. You ended up having to work this way because of the generic repository pattern. This pattern is actually an anti-pattern. It seems nice at first until you get to the point you're at. Instead you should create repositories for each of your entities that handle all CRUD operations for that entity. In these repositories is where you'll place your 'GetEmailTrackingAddressesGroup' type methods. And then your service layer can handle interacting with more that one repository if need be. Your service classes shouldn't have hard coded instances of your repositories. Instead you should be inject repository interfaces into your service's constructor.
Here's an example of how I would set up repositories and a simple service that interacts with 2 repositories.
public interface IUserRepository
{
void Insert(User user);
...
IEnumerable<User> GetByDepartmentId(int deptId);
}
public interface IContactLogRepository
{
void Insert(ContactLog contactLog);
}
public class EmailService
{
private readonly IUserRepository _userRepo;
private readonly IContactLogRepository _contactLogRepo;
public EmailService(IUserRepository userRepo, IContactLogRepository contLogRepo) {
_userRepo = userRepo;
_contactLogRepo = contLogRepo;
}
public void EmailDepartment(int deptId, string message) {
var employees = _userRepo.GetByDepartmentId(deptId);
foreach (var emp in employees) {
Email(emp.Email, message);
_contactLogRepo.Insert(new ContactLog {
EmployeeId = emp.Id,
Message = message
});
}
}
private void Email(string address, string message) {
...
}
}
So our repositories are there to handle CRUD operations for a specific entity - not our service layer. The generic repository pattern forces us to do CRUD (well at least the retrieval) in our services.
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