reusing services calls in unit of work pattern - c#

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.

Related

Dependency Injection for singelton class with properties

I am having a custom context class in my ASP.NET 4.8 Framework website:
public sealed class MyCustomContext
{
private static readonly Lazy<MyCustomContext> staticContext =
new Lazy<MyCustomContext>(() => new MyCustomContext());
private MyCustomContext()
{
}
public static MyCustomContext Current => staticContext.Value;
public HttpContext Context => HttpContext.Current;
// Logic to return current user based on logged in user
public User LoggedInUser => ...
// Logic to return SiteWideSettings
public Collection<SiteWideSettings> SiteWideSettings => ...
}
The above class is a Singleton and the usage of the above class in my service class methods is like this:
public class MyService : IMyService
{
public MyService()
{
}
public void DoWork()
{
var current = MyCustomContext.Current;
var loggedInUser = current.LoggedInUser;
var siteWideSettings = current.SiteWideSettings;
var currentContext = current.Context;
// use the above properties further for this method
}
}
My goal is to remove MyCustomContext class dependency hardcoded in my DoWork method of MyService class so that it can look like this:
public class MyService : IMyService
{
private readonly IMyCustomContext _myCustomContext;
public MyService(IMyCustomContext myCustomContext)
{
_myCustomContext = myCustomContext;
}
public void DoWork()
{
var current = _myCustomContext.Current;
var loggedInUser = current.LoggedInUser;
var siteWideSettings = current.SiteWideSettings;
var currentContext = current.Context;
// use the above properties further for this method
}
}
Can you share how to convert my MyCustomContext class so that it can be injected via dependency injection into MyService?
I have one more question, do the properties like LoggedInUser, SiteWideSettings and Context of MyCustomContext class should be written as properties or they should be converted to methods for dependency injection?
For the dependency injection you need an interface which gets initialized, so your MyCustomContext class needs to implement a new interface called IMyCustomContext. The interface can look like following:
public interface IMyCustomContext
{
HttpContext Context { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
public class MyCustomContext : IMyCustomContext
{
public HttpContext Context
{
get { return HttpContext.Current; }
}
public User LoggedInUser
{
get
{
// Logic to return current user based on logged in user
}
}
public Collection<SiteWideSettings> SiteWideSettings
{
get
{
// Logic to return SiteWideSettings
}
}
}
In the Startup.cs there is a method called ConfigureServices, there you can add the following for the dependency injection:
container.RegisterType<IMyCustomContext, MyCustomContext>(
TypeLifetime.Singleton);
It's worth pointing out that Singleton has dual meaning here:
The Singleton Design Pattern ensures an object is only instantiated once. Its implementation isn't ideal though, as it relies on ambient state.
The Singleton Lifetime is used by IOC frameworks, where it ensures the same reference of an object is used every time.
In short, the Singleton Lifetime effectively removes the need to implement the Design Pattern, because the IOC framework ensures the backing concept for you.
Meaning, if we register our dependency with the Singleton Lifetime.
container.RegisterType<ICustomContext, MyCustomContext>(TypeLifetime.Singleton);
We can remove the code for the Singleton Pattern, as the IOC container will take over the responsibility of guarding the single instance/reference.
public class MyCustomContext : ICustomContext
{
public HttpContext Context => HttpContext.Current;
// Logic to return current user based on logged in user
public User LoggedInUser => ...
// Logic to return SiteWideSettings
public Collection<SiteWideSettings> SiteWideSettings => ...
}
I've also added the ICustomContext interface with the member we're interested in.
public interface ICustomContext
{
HttpContext Context { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
Can you share how to moq properties of that class?
That's right, we just moved the problem one level, didn't we? If you need to extract an interface, you usually need to do this in a recursive manner.
This also means HttpContext is not a good candidate for an interface member, which makes sense when you think about it. From a unit test's point of view, we're not interested in verifying ASP.NET's inner workings. Instead, we want to check our own code, and only that portion, with no dependencies on foreign libraries. To do so, you should only copy the HttpContext members you need on to your interface and remove the dependency on HttpContext (which is notoriously hard to abstract).
For example:
public interface ICustomContext
{
IPrincipal User { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
This will require some refactoring / remodeling as the number of properties grows.
For simple DTO's you can even choose not to abstract / interface them, as long as your able to easily create fakes for unit testing. Also remember it only makes sense to introduce an interface if there are going to be multiple implementations.
One more thing about Dependency Inversion, and how IOC frameworks work, you usually let the dependencies bubble up. The recommended approach is through constructor injection, as illustrated in the following ICustomContext implementation for unit tests.
public class TestCustomContext : ICustomContext
{
public MyCustomContext(IPrincipal user, User loggedInUser, Collection<SiteWideSettings> siteWideSettings)
{
User = user;
LoggedInUser = loggedInUser;
SiteWideSettings = siteWideSettings;
}
IPrincipal User { get; }
User LoggedInUser { get; }
Collection<SiteWideSettings> SiteWideSettings { get; }
}
I have one more question, do the properties like LoggedInUser, SiteWideSettings and Context of MyCustomContext class should be written as properties or they should be converted to methods for dependency injection?
You can have both. If the state was injected through constructor injection, you might as well expose it as a property. If the implementing class implements behavior to create / transform the state, you might want to expose the behavior as a method. It all depends on the actual case, there is no golden bullet here. Just remember that in OO design, interfaces are used to model behaviors, with their scope kept as small as possible.
UPDATE
Those properties are not getting filled via constructor. All of these properties "IPrincipal User { get; } User LoggedInUser { get; } Collection SiteWideSettings { get; }" have the body in their getter, they get the data from cache first and if not found then it calls the service to get the data from db for those properties (all that is written in in the get of those properties). Should I keep them as properties only or make them methods?
Let me split up your question.
Should I keep them as properties only or make them methods?
From a technical point of view, it doesn't really matter. Properties, or automated properties (like the ones you're using), are just syntactic sugar over full blown methods. Meaning, they all get compiled into equivalent CIL instructions.
That leaves only the human factor. The readability and maintainability of your code. The agreed upon coding style and practices. That's not something I can answer for you. Personally, I prefer methods for handling these kind of code flows.
they get the data from cache first and if not found then it calls the service to get the data from db for those properties (all that is written in in the get of those properties).
Sounds like this class is more of a service provider than an actual model class in your domain. As there's also I/O involved, I'd definitely recommend switching to asynchronous methods on your interface. The explicit (Task based) signature says a lot to fellow developers reading your code.
The part where I talked about the dependencies bubbling up plays an important role here. The cache and repository are both dependencies of MyCustomContext. IOC and its inherent Dependency Inversion Principle rely on the explicit declaration of dependencies, as shown in the following sample. Note the implementation of GetLoggedInUser() is not what matters here, rather the way the dependencies are set through the constructor. All these dependencies need to be registered with your IOC container first, for it to be able to resolve ICustomContext.
public class MyCustomContext : ICustomContext
{
private readonly IUsersCache _usersCache;
private readonly IUsersRepo _usersRepo;
public MyCustomContext(IUsersCache usersCache, IUsersRepo usersRepo, IPrincipal principal)
{
_usersCache = usersCache;
_usersRepo = usersRepo;
Principal = principal;
}
public IPrincipal Principal { get; }
public async Task<LoggedInUser> GetLoggedInUser()
{
var userId = await GetUserId(Principal);
var user = _usersCache.GetById(userId);
if (user == null)
{
user = _usersRepo.GetById(userId);
_usersCache.Add(user);
}
return user;
}
...
}
Those properties are not getting filled via constructor. All of these properties "IPrincipal User { get; } User LoggedInUser { get; } Collection SiteWideSettings { get; }" have the body in their getter
I don't think that's true for IPrincipal as it, together with HttpContext, is instantiated by ASP.NET behind the scenes. All you need to do is tell the IOC container how to resolve the current IPrincipal and let it work its magic.
Likewise, all classes that depend on ICustomContext should have it injected by the IOC container.
public class MyService : IMyService
{
private readonly ICustomContext _customContext;
public MyService(ICustomContext customContext)
{
_customContext = customContext;
}
public async Task DoWork()
{
var currentPrincipal = _customContext.Principal;
var loggedInUser = await _customContext.GetLoggedInUser();
...
}
}
An important part here is again unit testing. If you design your classes like this, you can easily create fakes for testing. And even if there wasn't any testing involved, which I wouldn't recommend, the ability to decouple classes like this is a good indication of a well designed code base.

How to write unit tests for proxy pattern?

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.

Test-Friendly Architecture

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.

Is it a good design to inject services as factories?

I have been reading Mark Seemann's excellent book on DI and hope to implement it in my next WPF project. However I have a query regarding object lifetime. So far, most examples seem to explain the repository pattern per request for MVC applications. In WPF there isn't really an alternative to this (I think). Seeing as the object graph of the entire application is constructed in the composition root, how can I make sure that my unit-of-work stuff is working properly. For example:
public class ContextFactory : IContextFactory
{
DBContext context;
public ContextFactory()
{
context = new MyDBContext();
}
public DBContext GetContext()
{
return context;
}
}
public class ItemOneRepository() : IItemOneRepository
{
DBContext context;
public ItemOneRepository(IContextFactory contextFactory)
{
this.context = contextFactory.GetContext();
}
public IEnumerable GetItems()
{
return context.ItemOnes;
}
}
public class ItemTwoRepository() : IItemTwoRepository
{
DBContext context;
public ItemTwoRepository(IContextFactory contextFactory)
{
this.context = contextFactory.GetContext();
}
public IEnumerable GetItemsByItemOneID(int itemOneID)
{
return context.ItemTwos.Where(i => i.itemOneID == itemOneID);
}
}
public class ThingService : IThingService
{
IItemOneRepository itemOneRepo;
IItemTwoRepository itemTwoRepo;
public ThingService(
IItemOneRepository itemOneRepository,
IItemTwoRepository itemTwoRepository)
{
itemOneRepo = itemOneRepository;
itemTwoRepo = itemTwoRepository;
}
public IEnumerable Things GetThing()
{
var ItemOnes = itemOneRepo.GetItems();
return ItemOnes.Select(i =>
new Thing(
i.FieldOne,
i.FieldFour,
itemRepoTwo.GetItemsByItemOneID(i.ID)
)
);
}
}
In this case the MyDBContext instance is created through ContextFactory in the composition root. ItemOneRepository and ItemTwoRepository are using the same unit-of-work (MyDBContext), but so is the rest of the application which is plainly wrong. What if I changed the repositories to accept a DBContext instead of ContextFactory and added a ThingServiceFactory class like:
public ThingServiceFactory : IThingServiceFactory
{
IContextFactory contextFactory;
public ThingServiceFactory(IContextFactory factory)
{
contextFactory = factory;
}
public IThingService Create()
{
MyDBContext context = contextFactory.Create();
ItemOneRepository itemOneRepo = new ItemOneRepository(context);
ItemOneRepository itemTwoRepo = new ItemTwoRepository(context);
return new ThingService(itemOneRepo, itemTwoRepo);
}
}
This is better as I can now pass the ThingServiceFactory to my ViewModels instead of an instance of ThingService (complete with DBContext). I can then create a unit-of-work whenever I need one and instantly dispose of it when I’ve finished. However, is this really the correct approach. Do I really need to write a factory for every unit-of-work operation I need? Surely there is a better way...
There's IMO only one good solution to this problem and that is to apply a command-based and query-based application design.
When you define a single ICommandHandler<TCommand> abstraction to define business transactions, you can inject closed versions of that interface into any form that needs this. Say for instance you have a "move customer" 'command' operation:
public class MoveCustomer
{
public Guid CustomerId;
public Address NewAddress;
}
And you can create a class that will be able to execute this command:
public class MoveCustomerHandler : ICommandHandler<MoveCustomer>
{
private readonly DBContext context;
// Here we simply inject the DbContext, not a factory.
public MoveCustomerHandler(DbContext context)
{
this.context = context;
}
public void Handle(MoveCustomer command)
{
// write business transaction here.
}
}
Now your WPF Windows class can depend on ICommandHandler<MoveCustomer> as follows:
public class MoveCustomerWindow : Window
{
private readonly ICommandHandler<MoveCustomer> handler;
public MoveCustomerWindows(ICommandHandler<MoveCustomer> handler)
{
this.handler = handler;
}
public void Button1Click(object sender, EventArgs e)
{
// Here we call the command handler and pass in a newly created command.
this.handler.Handle(new MoveCustomer
{
CustomerId = this.CustomerDropDown.SelectedValue,
NewAddress = this.AddressDropDown.SelectedValue,
});
}
}
Since MoveCustomerWindow lives for quite some time, it will drag on its dependencies for as long as it lives. If those dependencies shouldn't live that long (for instance your DbContext) you will be in trouble and Mark Seemann calls this problem Captive Dependency.
But since we now have a single ICommandHandler<TCommand> abstraction between our presentation layer and our business layer, it becomes very easy to define a single decorator that allows postponing the creation of the real MoveCustomerHandler. For instance:
public class ScopedCommandHandlerProxy<TCommand> : ICommandHandler<TCommand>
{
private readonly Func<ICommandHandler<TCommand>> decorateeFactory;
private readonly Container container;
// We inject a Func<T> that is able to create the command handler decoratee
// when needed.
public ScopedCommandHandlerProxy(
Func<ICommandHandler<TCommand>> decorateeFactory,
Container container)
{
this.decorateeFactory = decorateeFactory;
this.container = container;
}
public void Handle(TCommand command)
{
// Start some sort of 'scope' here that allows you to have a single
// instance of DbContext during that scope. How to do this depends
// on your DI library (if you use any).
using (container.BeginLifetimeScope())
{
// Create a wrapped handler inside the scope. This way it will get
// a fresh DbContext.
ICommandHandler<TCommand> decoratee =this.decorateeFactory.Invoke();
// Pass the command on to this handler.
decoratee.Handle(command);
}
}
}
This sounds a bit complex, but this completely allows you to hide the fact that a new DbContext is needed from the client Window and you hide this complexity as well from your business layer; you can simply inject a DbContext into your handler. Both sides know nothing about this little peace of infrastructure.
Of course you still have to wire this up. Without a DI library you do something like this:
var handler = new ScopedCommandHandlerProxy<MoveCustomerCommand>(
() => new MoveCustomerCommandHandler(new DbContext()),
container);
How to register this in a DI library is completely depending on the library of choice, but with Simple Injector you do it as follows:
// Register all command handler implementation all at once.
container.Register(
typeof(ICommandHandler<>),
typeof(ICommandHandler<>).Assembly);
// Tell Simple Injector to wrap each ICommandHandler<T> implementation with a
// ScopedCommandHandlerProxy<T>. Simple Injector will take care of the rest and
// will inject the Func<ICommandHandler<T>> for you. The proxy can be a
// singleton, since it will create the decoratee on each call to Handle.
container.RegisterDecorator(
typeof(ICommandHandler<>),
typeof(ScopedCommandHandlerProxy<>),
Lifestyle.Singleton);
This is just one of the many advantages that this type of design gives you. Other advantages is that it makes much easier to apply all sorts of cross-cutting concerns such as audit trailing, logging, security, validation, de-duplication, caching, deadlock-prevention or retry mechanisms, etc, etc. The possibilities are endless.
ItemOneRepository and ItemTwoRepository are using the same
unit-of-work (MyDBContext), but so is the rest of the application
which is plainly wrong.
If your factory is registered with a transient lifecycle, you will get a new instance every time it's injected, which will be a new DBContext each time.
However, I would recommend a more explicit unit of work implementation:
public DBContext GetContext() //I would rename this "Create()"
{
return new MyDBContext();
}
And:
public IEnumerable GetItemsByItemOneID(int itemOneID)
{
using (var context = contextFactory.Create())
{
return context.ItemTwos.Where(i => i.itemOneID == itemOneID);
}
}
This gives you fine-grained control over the unit of work and transaction.
You might also ask yourself if the repositories are gaining you anything vs. just using the context directly via the factory. Depending on the complexity of your application, the repositories may be unnecessary overhead.

Design pattern for API entry point?

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

Categories

Resources