Requirement:
I have requirement to integration with multiple payment gateways. However the client uses only one of the available, and that is configured using admin settings.
Current System:
I have written one library each per payment gateway. Which creates a maintenance nightmare and potential increase in projects as the gateway integration requests (sources) increase.
Question
Can someone suggest me a design pattern to use in this scenario, to may be create interfaces and common settings and implement the gateway as required which reduces duplicate code?
I would create a standard interface to deal with the common operations. Have a set of domain objects that are passed into those methods.
For example, to create a payment you might have a PaymentCardDetails model, an AddressModel etc. Your interface would have a method MakePayment or similar, e.g.:
public MakePaymentResponse MakePayment(PaymentCardDetails cardDetails, AddressModel address);
Then each of your payment gateways should implement this interface using their own implementation.
Then use IoC (Inversion of Control) / DI (Dependency Injection) to decide which interface to use at runtime based on a provided config value.
In the methods in your code that use the payment gateways you would pass in the interface using constructor injection, your DI framework would take care of picking the right implementation. e.g.
public class Payment {
private readonly IPaymentGateway _paymentGateway;
public Payment(IPaymentGateway paymentGateway) {
_paymentGateway = paymentGateway;
}
public MyMethod() {
//get your models prepared etc.
_paymentGateway.MakePayment(cardDetails, addressDetails);
}
Related
The typical architecture I am using consists of Manager objects in the Business Layer. I am using DI/IOC within .NET Core/ .NET Standard. The managers are injected into the service layer and consequently the services are injected into our API controllers. So I am presently working in a Manager class. I now need a method that resides in another manager class.
Usually I return back through the service layer to the controller, then call the next service and then the manager through that.
I am wondering whether it is OK to just inject a Manager I require directly into the Manager I am working in. Therefore cutting out the trip back to the controller and then back up through the other service to the other manager. Basically I have 2 * Managers.
public class TypeCodeManager : ITypeCodeManager
{
public TypeCodeManager()
{
}
public async Task<int> GetTypeCodeAsync(string typeCode, string code)
}
public class UserManager : IUserManager
{
private readonly ITypeCodeManager _typeCodeManager;
public UserManager(ITypeCodeManager typeCodeManager)
{
_typeCodeManager = typeCodeManager
}
}
Is this generally a good idea?
I would say it's generally not a good idea to cross over into other domains through the "managers", assuming that your managers are what talks to the persistence layer. This will quickly lead to confusing dependency maps and code.
Your services are a much better layer to orchestrate the cross-domain concerns as they may describe cross domain workflows and depend on multiple managers.
I've been trying to learn how the service layer and repository pattern work. So far I've written a service layer and a simple repository pattern interface. However, I often see articles stating that the repository pattern allows for being able to swap in and out different data stores without the consuming code having to be changed.
In my case I want to be able to support reading and writing the application data to CSV and/or XML files. This is the part where I do not understand how to properly implement this with the repository pattern. Should I have a repository per data store?
ProductCsvRepository : IProductRepository
ProductXmlRepository : IProductRepository
However if I do this then the service layer would have to be aware of the underlying data store, which breaks the idea of being able to easily swap in and out different data stores.
Would I then have to have a service layer that looks like this?
private readonly IProductXmlRepository _productXmlRepository;
private readonly IProductCsvRepository _productCsvRepository;
public ProductService()
{
_productXmlRepository = new IProductXmlRepository();
_productCsvRepository = new IProductCsvRepository();
}
public ICollection<Product> GetAllXml()
{
return _productXmlRepository.GetAllCsv();
}
public ICollection<Product> GetAll()
{
return _productCsvRepository.GetAllXml();
}
This then raises two questions:
Surely this then breaks the idea of the consuming code needing to know what the data store is?
What about in the situations where the consuming code does need to know about the data store, such as for "File > Export As" type functionality? Should export functionality actually be a different service that utilises the appropriate CSV or XML service?
I think I am definetly not understanding how to correctly implement a repository patten and a service layer. How should I actually design repository patten and service layer?
Take a look at dependency injection and the plug-in pattern. They support injecting a concrete implementation of a repository. Your service layer then has only one reference to IProductRepository and a concrete repository gets injected. Something along the lines of this:
public class ProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
}
public class ConsumingClass {
{
private readonly IProductService _productService = new ProductService(new ProductXmlRepository());
// methods to use the the product service
}
But better would be to use a inversion of control container like NInject or SimpleInjector. Those frameworks can be used to link abstract classes (IProductRepository) to concrete classes (ProductXmlRepository or ProductXmlRepository) based on xml configurations.
Your application's solution should be structured following the Dependency Inversion Principle (http://deviq.com/dependency-inversion-principle/), so that there are at minimum three projects:
Core
Infrastructure
Your UI project
All (or nearly all) of your interfaces should be declared in Core (e.g. IProductRepository). Your interface implementations belong in Infrastructure, which references Core. Finally, your UI project should reference Core, but not necessarily Infrastructure (learn how to use types from a project without referencing it: http://blog.falafel.com/use-types-from-project-without-referencing/).
With this architecture in place, you can use dependency injection (http://deviq.com/dependency-injection/) to inject the desired implementation of a given type at runtime, which provides great flexibility and testability.
Setting up your solution with the proper dependencies between projects is critical to being successful with this approach, since a traditional UI -> Business Layer -> Data Layer setup will not allow you to invert dependencies. Once your solution is set up in this manner, you should follow the Explicit Dependencies Principle (http://deviq.com/explicit-dependencies-principle/) in all of your UI and service code.
I have an application which uses an IPaymentService to process credit card payments. The appropriate implementation (CreditCardPaymentComponent or CheckPaymentComponent or anything else that implements the IPaymentService interface) is injected into the application by a PaymentProvider using the ASP.NET Provider Model.
We also need these components to be reusable for different applications which may not have access to the PaymentProvider.
The question is where to put the IPaymentService interface? It can't be inside the application because there are multiple applications which need to use the service. It can't be inside the service because there are multiple services which implement this interface. I don't like putting the interfaces in their own project because then I have to add references everywhere. Is there another solution?
EDIT: To clarify, the point of using the Provider Model is so we can support other developers, so they can write for example CustomPaymentComponent which implements IPaymentService and it works seamlessly with our app. I am leaning towards #Frazell's answer but I am just wondering if there is any downside to putting IPaymentService in the same assembly with the PaymentComponents? If you had to develop a CustomPaymentComponent for this system, what would make the most sense to you?
You can't escape having to have the interface and the implementation code referenced where it is needed. If the payment code has to be reusable in many applications I would break it out into a separate library (dll) and package it appropriately.
Managing the additional assembly is a lot easier than resorting to code duplication, which is the only alternative. Duplication has to be avoided at all costs.
Depending on what you're doing overall. I would provide the interface and base implementations in the same assembly (such as a payments assembly) and allow use of DI to swap out the implementations where needed in edge case scenarios.
The solution is actually quite simple:
Use the adapter pattern.
You don't let the components implement that interface at all, but implement adapters for each component based on that interface. In that case the adapter and interface can be placed together:
class CreditCardPaymentServiceAdapter : IPaymentService
{
private CreditCardPaymentService service;
public CreditCardPaymentServiceAdapter(
CreditCardPaymentService service)
{
this.service = service;
}
// Implement IPaymentService here and forward
// to the CreditCardPaymentService.
}
This adapter itself will contain no business logic, but will just map/transform/adapt to the real CreditCardPaymentService and exposed the IPaymentService (or which interface is suited for that application).
If you have multiple applications, you might be forced to duplicate these adapters and the interface. That's the downside.
I'm relatively new the world of Microsoft WCF. I have a few questions regarding the best design pattern/method to use to implement one or more services that will address my needs.
I have an existing DataLayer which I would like to push into 1 or more WCF services. The backend database is ORACLE (and I have an entire data access layer which communicates with the correct version of ODAC).
When I look at my existing datalayer, I (more or less) have support for mulitple data objects (classes).
UserInfo
UserActivityHistoryAudit
Evaluations
EvaluationWorkFlowAndReview
EvaluationReports
I have several questions involving the best way to implement this in WCF.
Is it best to implement this as one service or several services (one which coincides with each data class/functionality)?
Ultimately, I would like to share the underlying Data Access layer which communicates with the ORACLE ODAC library. Is it best to embed this in a shared library, assembly?
If I go with multiple services, is it cleaner to hang them all off of the same endpoint?
What is the best strategy to use when designing this?
Thanks,
JohnB
the best way is to use one service that is WCF Data Service (OData)
here a sample you can download
http://code.msdn.microsoft.com/WCF-Data-Service-OData-ebb4214a
Often times, your business layer will also be implemented on the server. In such an event, you will simply wrap your business layer. If you do not have a business layer on the server side, model your service based on the same concept. You are exposing a set of functionality to target a specific consumer (or set of consumers). You will generally have one service to present to each consumer (or set of consumers). With that being said, you do not want one large monolithic service just to cover all of your potential needs. Break it down into logical areas.
Most of the time, wrapping a single data layer object is too small to wrap by itself. The exception is if you are simply servicing the data generically to everyone (very common with REST and ODATA services).
===========================
Model your services based off of consumption needs. One service per consumer set.
If you will be sharing your data layer across multiple business layers in different binaries, the data layer should exist in its own stand alone library and shared.
The endpoint layouts for your services are not generally important as long as you are consistent. At the end of the day, your consumers will simply copy/paste the endpoint that you provide.
Have you considered using Factory and Repository Pattern? Something like this.
`public interface IEmployee
{
// define your model here (properties, for example)
string FirstName {get; set;}
string LastName {get; set;}
}
public interface IEmployeeBizFactory
{
IEmployee CreateEmployee();
}
public class CustomEmployee : IEmployee
{
// Implementation here
}
public class CustomEmployeeBizFactory : IEmployeeBizFactory
{
public IEmployee CreateEmployee()
{
return new CustomEmployee();
}
}`
Consider Data Contracts for each of your data objects
Using Data Contracts
I am maintaining an ASP.NET MVC project. In the project the original developer has an absolute ton of interfaces. For example: IOrderService, IPaymentService, IEmailService, IResourceService. The thing I am confused about is each of these is only implemented by a single class. In other words:
OrderService : IOrderService
PaymentService : IPaymentService
My understanding of interfaces has always been that they are used to create an architecture in which components can be interchanged easily. Something like:
Square : IShape
Circle : IShape
Furthermore, I don't understand how these are being created and used. Here is the OrderService:
public class OrderService : IOrderService
{
private readonly ICommunicationService _communicationService;
private readonly ILogger _logger;
private readonly IRepository<Product> _productRepository;
public OrderService(ICommunicationService communicationService, ILogger logger,
IRepository<Product> productRepository)
{
_communicationService = communicationService;
_logger = logger;
_productRepository = productRepository;
}
}
These objects don't seem be ever be created directly as in OrderService orderService = new OrderService() it is always using the interface. I don't understand why the interfaces are being used instead of the class implementing the interface, or how that even works. Is there something major that I am missing about interfaces that my google skills aren't uncovering?
This particular design pattern is typically to facilitate unit testing, as you can now replace OrderService with a TestOrderService, both of which are only referenced as IOrderService. This means you can write TestOrderService to provide specific behavior to a class under test, then sense whether the class under test is doing the correct things.
In practice, the above is often accomplished by using a Mocking framework, so that you don't actually hand-code a TestOrderService, but rather use a more concise syntax to describe how it should behave for a typical test, then have the mocking framework dynamically generate an implementation for you.
As for why you never see 'new OrderService' in the code, it's likely that your project is using some form of Inversion of Control container, which facilitates automatic Dependency Injection. In other words, you don't have to construct OrderService directly, because somewhere you've configured that any use of IOrderService should automatically be fulfilled by constructing a singleton OrderService and passing it in to the constructor. There are a lot of subtleties here and I'm not exactly sure how your dependency injection is being accomplished (it doesn't have to be automatic; you can also just construct the instances manually and pass them in through the constructors.)
That's not the only use of interfaces, in MVC they are being used to decouple contract from implementation. To understand about MVC you need to read up a bit on the related topics such as separation of concerns and inversion of control (IoC).The actual act of creating an object to be passed to OrderService constructor is handled by IoC container based on some predefined mapping.
These objects don't seem be ever be created directly as in OrderService orderService = new
OrderService()
So waht?
Point is that SOMEONE calls the OrderService constructor and THE CALLER is respónsible for creating them. He hands them over.
I don't understand why the interfaces are being used instead of the class implementing the
interface
Because you want not to know the class - it may change, be external, be configurable using an IOC container and the programmer decided to not require even a common base class. THe less assumptions you make about how someone implements used utility classes, the better.
Is there something major that I am missing about interfaces that my google skills aren't
uncovering?
No, bu a good book about OO programming would help more than random google snippets. This baiscally falls into the architecture area and .NET basics (for the first part).
It's good practice to program against interfaces rather than objects. This question gives good reasons why, but some reasons include allowing the implementation to change (ex. for testing).
Just because there's currently only 1 class that implements the interface doesn't mean that it can't change in the future.
Furthermore, I don't understand how these are being created and used.
This is called dependency injection and basically means that the class doesn't need to know how or where to instantiate it's dependencies from, someone else will handle it.
These are service interfaces, which encapsulate some kind of externality. You often have just a single implementation of them in your main project, but your tests use simpler implementations that don't depend on that external stuff.
For example if your payment service contacts paypal to verify payments, you don't want to do that in a test of unrelated code. Instead you might replace them with a simple implementation that always returns "payment worked" and check that the order process goes through, and another implementation that returns "payment failed" and check that the order process fails too.
To avoid depending on the implementation, you don't create instances yourself, you accept them in the constructor. Then the IoC container that creates your class will fill them in. Look up Inversion of Control.
Your project has probably some code that sets up the IoC container in its startup code. And that code contains information about which class to create when you want an implementation of a certain interface.