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.
Related
We have a web api project which references a library that in turn is shared between many different systems.
The library exposes a "RegisterDependancies(IWindsorContainer container)" function that when called will register all of the dependencies for that particular library.
So when the web api application starts it does its own registrations and then calls the shared library, something like the following pseudo code :
public void SetupWindsor(){
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<iFoo>().ImplementedBy<Foo>());
SharedLibrary.RegisterDependancies(container);
}
The shared library function looks a bit like this:
public void RegisterDependancies(IWindsorContainer container)
{
container.Register(Component.For<iBar>().ImplementedBy<Bar>());
//In this instance Bar is internal so could not be registered by the api project.
}
We now want the web api project to use the PerWebRequest lifestyle but other systems may want to use a different lifestyle (This decision will be down to whoever writes the client app - the shared library will be used in console and windows apps - so perwebrequest isn't suitable for them to use)
We want to change the RegisterDependancies method so that we can pass in the lifestyle.
Is it possible to do this with the PerWebRequest lifestyle? A few of us had a look and couldnt see how to do it - despite having done similar without issues with unity in the past.
We are either looking for a way to resolve the problem in the way described, or if there is a better way to approach this that would also be helpful.
Edit to clarify, the shared library defines the interface IBar as public but the class Bar as internal so the API cannot do the registration - unless there is some magic in windsor that I am unaware of.
the shared library defines the interface IBar as public but the class Bar as internal so the API cannot do the registration
Let's examine that design decision for a moment. While no external callers can create a Bar object, they can create an IBar object:
IWindsorContainer container = new WindsorContainer();
SharedLibrary.RegisterDependancies(container);
IBar bar = container.Resolve<IBar>();
There can be various reasons to keep the Bar class internal, but since you can already run code like the above, why not simply let the shared library expose a factory?
IBar bar = SharedLibrary.CreateBar();
That'd be much simpler and decouple the shared library from the container. In general, that's the best advice I can give regarding Dependency Injection and reusable libraries: Use Dependency Injection patterns, not containers. See my article DI-Friendly Library for more details.
If you still want to use a DI Container in your host project (e.g. Wep API project), you can register IBar against that static factory method.
Internal classes
There are legitimate reasons why one would want to keep some classes internal, but I often see code bases where classes are internal for no apparent reason. My experience with decades of C# code is that the cases where classes are internal for no good reason far outweighs the cases where there's a good reason.
Does Bar really have to be internal? Why?
From the OP it's clear that IBar is implemented by Bar. This could be an artefact of reducing the question to essentials (good job doing that, BTW), but I get the impression that Bar is the only class that implements IBar. Is that the case?
If so, the Bar class must expose the methods defined by IBar. Thus, the API of the class is already public, so why hide the class? The only thing hidden, then, is the constructor...
The perfect storm
Sometimes when I give advice like the above, I'm met with a response that that's not what the question was about. The question is about how to change Castle Windsor lifestyles (which, BTW, you can).
This question, on the other hand, is almost the perfect (little) storm that illustrates why reusable libraries shouldn't depend on DI Containers:
The library should be usable in more than one context (web, console, desktop, etc.)
The library depends on Castle Windsor
Interfaces are public, but implementation classes aren't
This complicates things - hence the question here on Stack Overflow.
My best advice is to keep things simple. Removing the dependency on Castle Windsor will make library development and reuse easier, not harder.
It'd be even easier to use the library if you make most library classes public.
You can set the lifestyle on the component registration using LifeStyle.Is(LifestyleType)
Something like this will allow you to pass the lifecycle in.
public void RegisterDependencies(IWindsorContainer container, Castle.Core.LifestyleType lifestyleType)
{
container.Register(Component.For<IBar>().ImplementedBy<Bar>().LifeStyle.Is(lifestyleType));
}
Alternatively, take a look at registering by convention with the assembly, this would allow control of the lifestyle from within the API project without needing a public implementation
https://github.com/castleproject/Windsor/blob/master/docs/registering-components-by-conventions.md
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'm trying to do dependency injection throughout the app tier and am running into a scenario I'm sure others have seen. There are some 3rd party web services that we consume and the clients were auto-generated with a base class. The clients do not have an interface and the data types are in the same file/project.
The obvious problem is if I want to do unit testing I'll need to mock the service. I'll need to extract an interface and move the data types into a "contracts" project that is available to both real/mock clients. However, the next time the client is auto-generated that work needs to be redone. Creating a proxy at runtime wouldn't help much because then we would have to manually create the interfaces and data types from the WSDL. Is there a better way to handle this?
Extracting an interface from the implementation is not going to help you much anyway, as it's going to be a poor abstraction.
Interfaces should be defined and owned by the clients that consume the interfaces. As Agile Principles, Patterns, and Practices explain, "clients […] own the abstract interfaces" (chapter 11). Thus, any attempt to define a data-centric interface like extracting interfaces from auto-generated web service clients is bound to cause problems sooner or later, because it's violating various SOLID principles like the Dependency Inversion Principle or the Interface Segregation Principle.
Instead, your client code should define the interfaces that they require. Then you can always implement those interfaces with the auto-generated web service clients. If you've used Microsoft's tooling (Visual Studio, wsdl.exe, etc.) the relevant auto-generated class should already be a partial class, which means you should be able to add behaviour to it without touching the auto-generated part of it.
I have read other questions about circular references on here but I can't find the answer to my question.
I have three class libraries: Authentication, EmailService and ExceptionService.
Authentication controls user login to various applications, EmailService sends emails, the ExceptionService logs errors/exceptions to a database.
At the moment Authentication references the EmailService and the ExceptionService, to use their functionality, and this works. The ExceptionService references the EmailService to send report emails. All is well.
What I would like to know is if the following is possible/advisable/stupid, and if there is a better way to do it:
I want the EmailService to be able to use the functionality of the ExceptionService, so any errors in the EmailService are reported. In theory this could mean that the ExcpetionService would then call back to the EmailService to send the reporting email, which may trigger the same error, so I would have to write a method that was used by the EmailService only which did not send the email, only logged it.
The ExceptionService should still reference the EmailService.
The Authentication class library should also still use both of the other services.
This all sounds very complicated and circular, which is why I think it might not be a good thing to do. But what should I do instead?
I have tried referencing the ExceptionService in the EmailService, but it then will not compile when I create a private ExceptionService object and try to use it.
I suppose what I really want is for any of my applications to reference the EmailService and ExceptionService, but for them to also reference each other.
The only way of solving this that I have found so far is to forget about reporting exceptions in the EmailService.
Many thanks for your help :)
The reason you are having problems is because you are tightly coupling your classes and the compiler very sensibly gets upset when you try to create a circular coupling. You could solve this by making interfaces for your services and supplying an instance of the interface of one service to the implementation of the other and vice versa.
A much better solution though would be to cease reinventing the wheel and to use an existing logging framework. Both NLog and Log4Net will meet your logging and emailing needs.
Merge the assemblies. It is a common mistake to split a project into as many assemblies as possible. This adds management burden and causes trouble in case of cyclic references. Tight coupling is to be avoided, but it cannot be entirely avoided. Accept it.
Your situation is a valid case of a cyclic reference. The two classes just need each other for logical reasons.
You can resolve the cyclic reference issue with interfaces, but the dependencies still exists at runtime. The interfaces do not improve code quality, they just shut up the compiler warnings.
Do not manage dependencies with assemblies. Use namespaces and folders. Assemblies are deployment units, not dependency management tools.
The problem is that you uses concrete classes, not interfaces. So, my proposition is to introduce two interfaces i.e.:IExceptionService, IEmailService and place them in the separate project e.g.: Services. Projects containing implementations of these two services will reference this new project. Thanks to that ExceptionService can use IEmailService and EmailService can use IExceptionService. At the same time ExceptionService and EmailService can be defined in different assemblies.
What is important ExceptionService and EmailService shoudn't be aware what is behind these interfaces. The concrete implementations should be somehow injected into them. In order to do that you can use dependency injection container. If you don't want to use another new library, you can also implement simple service locator.
(I'm ignoring the AuthenticationService for now because it only muddles the issue - what you have is a simple circular dependency between two services - Exception and Email).
The best way to solve these circular dependency issues is by using a layer of interfaces and a repository.
Lets say you have two classes, EmailService and ExceptionService. They can't reference each other's DLL, so what you do, you create a third assembly, Interfaces, and create two interfaces for them, IEmailService and IExceptionService. Now your two classes can both reference only that shared Interfaces assembly.
Using some sort of Inversion of Control mechanism, your EmailService gets a reference to a IExceptionService, and vice versa, and thus the circle is broken.
One simple IoC mechanism is the Service Locator pattern. Create this (simplified) object:
public class ServiceLocator
{
public static IEmailService EmailService {get;set;}
public static IExceptionService ExceptionService {get;set;}
}
Now your EmailService, on startup, can register itself with the ServiceLocator, and allow other classes to get a reference to it, without having a dependency on its assembly.
Of course, most IoC solutions have a bit more to them than that, but that's the basic idea - prevent circular dependencies by extracting shared interfaces into a shared assembly, and reference only that.
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.