How to use dummy class for external API at runtime (configurable)? - c#

I need to fetch data from an external API, only accessible via VPN.
The development/test machine will not always be able to connect to the VPN.
The desired behaviour is to use two different implementations (one that calls the actual external API and one that acts as the real thing but returns dummy data). Which implementation to use will be configured via a flag in web.config
I've tried the IoC containers StructureMap and Unity and they both did the job but they only seem to be applicable for MVC, I'm looking for a generic solution that also works for web forms. And also, isn't it a bit overkill to use them for this isolated design problem!?
Is there a design pattern or best practice approach for this particular scenario?

IoC / dependency injection sounds like the correct approach, but you don't necessarily need a container for a simple scenario. The key is to have classes that depend on the API reference an interface IAPI, and pass it the actual implementation RealAPI or FakeAPI.
public class SomeClass
{
private readonly IAPI _api;
public SomeClass(IAPI api)
{
_api = api;
}
}
Now you should be able to switch out the implementation easily by passing a different object to MyClass. In theory, when you're using an IoC approach, you should only need to bind the interface to the implementation once, at the top level of the application.

isn't it a bit overkill to use them for this isolated design problem!?
They probably are. Those IoC containers only help you when you wrote loosly coupled code. If you didn't design your classes according to the SOLID principles for instance, those frameworks will probably only be in the way. On the other hand, which developer doesn't want to write loosly coupled code? In other words, IoC container solves a problem you might not have but it's a nice problem to have.
StructureMap and Unity [...] only seem to be applicable for MVC
Those ioc frameworks can be used in any type of application (as long as it is written in loosly coupled way). Some types of applications need a bit more work to plug a framework in, but it's always possible. StructureMap and Unity might only have integration packages for MVC, it's quite easy to use them in ASP.NET Web Forms as well.
Is there a design pattern or best practice approach for this
particular scenario?
What you're looking for is the Proxy pattern and perhaps the circuit breaker pattern.

Related

What framework uses `IServiceProvider`?

Is the IServiceProvider basically just a generic interface for any IOC container, or is it used for a specific framework? I'm rolling my own light weight IOC container and I am wanting to know if I should implement it. Are there any other interfaces that I should implement? I'm not really interested in either MEF or Unity. I've used both extensively and they don't really work for my current project.
IServiceProvider is an imported (or perhaps held-over) COM interface that is intended to be used for private features in the context of the object whom you interrogate for a Service. The term 'Service' is applied rather loosely here, it originally meant any COM object that could be returned based upon what GUID is given.
IServiceProvider # MSDN (.NET reference)
IServiceProviderImpl Class # MSDN (C++ ATL reference)
In .NET, you don't need to implement it unless you have a client that specifically supports it, and in many cases you won't need to add yet another level of indirection that is implied by using IServiceProvider. Also, you can devise your own scheme to share common objects or implement other use patterns based upon IoC / Dependency Injection that are more flexible or more rigid as dictated by your needs.
One good historical context for IServiceProvider is the IE Browser Plugin Spec. Here, it is used to allow plugin components to use Browser Host features in-context. In a COM context, this interface is useful because it hides the details of instantiation and also can be used as part of a object construction and utilization strategy to avoid reference loops.
WebBrowser Customization (Part 2) # MSDN
I think it is a pretty general use interface, so you can use it with anything. It almost should not even be in the Framework Class Library. For one specific use, Alex D. James of the WCF Data Services team has a blog about it.
http://blogs.msdn.com/b/alexj/archive/2010/01/07/creating-a-data-service-provider-part-2-iserviceprovider-datasources.aspx
I do not think it has anything to do with IoC containers. I have used Unity and Autofac quite a bit and have never seen it used with either. As for rolling your own, I would suggest you define your own container interface in the more standard generic way:
public interface IContainer
{
T Resolve<T>();
}
That is pretty standard with some variation, but you could also just use IServiceProvider if that fits your needs.
And on that note, unless this is just an academic exercise, you might want to read "Dependency Injection". Mark Seemann covers every container out there and quite a bit of theory and practice. That is, I highly recommend it.
https://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/
ASP.NET 5 uses IServiceProvider in "self-hosted" mode, that is, when hosting an ASP.NET application and the runtime in a console application or service.
(An object of type Microsoft.Framework.Runtime.Common.DependencyInjection.ServiceProvider -- which implements IServiceProvider -- is passed to your console app constructor.)
Thus, if you wanted to use a different IoC container in ASP.NET 5, you might want to implement this interface. Or wrap the other IoC container in a class which implements this interface.
The new (as of .NET 4) Runtime Caching API also uses it: http://msdn.microsoft.com/en-us/library/system.runtime.caching.objectcache.host.aspx.
And also Visual Studio designer.

Handling cross-cutting concerns like internal statistics reporting for components of a web application

I am trying to implement statistics reporting for internal components of an OLTP web application. For example, I want to track near real time the usage or performance of things like: number of successful/failed logins, number of nhibernate sessions, time to serve a HTTP request, number transactions of different types (orders, accesses, etc). All these stats are sent via UDP to a statsd server (https://github.com/etsy/statsd) and plotted as charts with Graphite.
The application is using dependency injection for wiring internal components. I want to centralize statistics reporting towards statsd server in a class of its own and hide it under an interface. However, I feel like injecting an instance of the stats reporting class/interface in every component of the application which is reporting performance or usage data to be a smell. It seems to me that performance reporting events should be something like a cross cutting concern, pretty much like logging.
How do you approach the internal design for such a request? Would you approach with constructor injection, static methods (e.g. PerformanceCounters.Increment("name.of.counter")) which are called my monitored components or how?
If it is of any help for context, the app is done in C# and is using ASP.NET and Castle Windsor as IoC.
Thanks,
Robert
I use Spring.Net for something like that. Spring is very like Castle Windsor for IoC, as far as I have heard of, and Spring uses CastleWindsor for creating dynamic proxies. These ones you can use for AOP, which is supported by Spring. The learning curve is short, the framework is very well documented. Once your performance aspect is configured, applying it to your methods should be more than easy. Let me know if you want a small sample.
The design pattern I think you are referring to is Aspect Oriented Programming. Castle Windsor supports AOP as do most other IoC containers.
You don't inject an instance of the stats reporting class/interface in every component, as you say. Rather, in your configuration, you wrap each component with an interceptor. The component knows nothing about stats reporting; the interceptor is invoked before and after every call to your component and can decide whether and where to send trace information. It's perfect for things like logging, tracing, performance counting, failure handling, and all those cross-cutting concerns you mention.

ASP.NET MVC3 Hand coding IoC

Ninject, Sprint.NET, Unity, Autofac, Castle.Windsor are all examples are IoC frameworks that are available. However, I like the learning curve and control of writing my own. It is definitely common practice to not "re-invent the wheel" and just use pre-existing structures. If your comment is along those lines please be gentle.
Can IoC be implemented without the use of XML? It seems to me most, if not all, of the aforementioned frameworks use XML but I would much rather just write mine in C# instead of using XML to load a .dll. The C# is all converted into one .dll eventually anyway.
From my understanding, if wrong please correct, IoC can be used with DI to make the functionality of classes be based off of their definition and implementation while allowing for a separation of concerns.
This is accomplished in C# using microsoft's library System.ComponentModel.IContainer by having a class which inherits it. A class, such as Product, would have an interface IProduct. A generic constructor would then inherit from IContainer and in the constructor, allow a repository to be passed in, an instantiated object to be passed in, and a function to be passed in. This would allow a controller action to then instantiate an interface (IProduct), instantiate the generic constructor with the current repository instance, and then pass it the interface and function.
Is this setup accurate?
I am still trying to learn more about this topic, and have read the wiki articles on IoC, DI, and read about Castle.Windsor, ninject, Unity, and looked over multiple definitions from the MSDN regarding C# libraries which are used. Any assistance, corrections, or suggestions, are greatly appreciated. Thanks
Can IoC be implemented without the use of XML?
Yes, Ninject, Unity, Castle Windsor and Autofac can be configured without using any XML at all. (not sure about Spring.NET, last time I used it it was impossible, version 1.3)
From my understanding, if wrong please correct, IoC can be used with
DI to make the functionality of classes be based off of their
definition and implementation while allowing for a separation of
concerns.
If under "IoC" you mean "IoC container" then yes, it can be used with DI, but since DI is a particular case of Inversion Of Control your IoC container will be just a container for you dependencies. By just having it your will not magically get any DI-friendly types. It's just a support for managing your inverted dependencies.
Edit
As Mystere Man pointed in his answer you need to improve you understanding of the IoC containers. So I would recommend to read this wonderful book (from Mark Seeman) about all that stuff.
I think it is a great exercise to start without a DI container. Before focusing on using a DI framework, focus on best patterns and practices. Especially, design all classes around Dependency Injection and make sure your code follows the SOLID principles. Both sounds pretty easy, but this takes a shift in mindset and a lot of practice before you will get this right (but is well worth it).
When you do this, and do this well, you will quickly notice that your application will evolve in amazing ways. Your code will be testable and extendable in ways that you never imagined before, without your code to rot over time (however, it keeps constant focus to prevent code from rotting).
Still, when you do all this right (which –again- takes a lot of practice), you will still have one part of your application that, despite your best efforts, will get more complex and harder to maintain, as the application grows. This is the part of the application where you wire all dependencies together: the Composition Root.
And this is where DI containers come in. They have fancy names and compete with each other over features, but their goal can be stated in a single sentence:
The goal of a DI container is to keep the Composition Root
maintainable.
Although you can write your own simple DI container to wire up your dependencies, to prevent your Composition Root to become a big fragile, ever changing ball of mud, the container must at least have one crucial feature: Automatic Constructor Injection (a.k.a. auto-wiring). With auto-wiring, the container will look at the constructor arguments of a type that it needs to create, and it will inject the dependencies in it based on the types of those arguments. This feature will make the difference between a maintenance nightmare and a healthy Composition Root. Although creating your own container that supports auto-wiring isn't that hard (with expression trees it takes about 20 lines of code), the moment you start needing auto-wiring is the time to start using one of the existing DI frameworks.
So in conclusion, if you feel it helps you in the learning experience by doing this by hand, please do, as long as you stick to SOLID, DI, DRY, and TDD. When the burden of changing your Composition Root for each change in the application gets too big (which will be sooner than you might expect), switch to an established framework.
I would suggest using an existing DI container first, to understand how it works from the end user perspective. Then you can go about re-designing the wheel. My favorite saying is "You have to know the rules before you can break them".
Some of what you've said doesn't make a lot of sense. you don't have to use System.ComponentModel.IContainer in any framekwork i know of. Maybe Unity requires that (Microsoft's container) but none of the others do. I'm not familiar with Unity thogh.

Does Dependency Injection (DI) rely on Interfaces?

This may seem obvious to most people, but I'm just trying to confirm that Dependency Injection (DI) relies on the use of Interfaces.
More specifically, in the case of a class which has a certain Interface as a parameter in its constructor or a certain Interface defined as a property (aka. Setter), the DI framework can hand over an instance of a concrete class to satisfy the needs of that Interface in that class. (Apologies if this description is not clear. I'm having trouble describing this properly because the terminology/concepts are still somewhat new to me.)
The reason I ask is that I currently have a class that has a dependency of sorts. Not so much an object dependency, but a URL. The class looks like this [C#]:
using System.Web.Services.Protocols;
public partial class SomeLibraryService : SoapHttpClientProtocol
{
public SomeLibraryService()
{
this.Url = "http://MyDomainName.com:8080/library-service/jse";
}
}
The SoapHttpClientProtocol class has a Public property called Url (which is a plain old "string") and the constructor here initializes it to a hard-coded value.
Could I possibly use a DI framework to inject a different value at construction? I'm thinking not since this.Url isn't any sort of Interface; it's a String.
[Incidentally, the code above was "auto-generated by wsdl", according to the comments in the code I'm working with. So I don't particularly want to change this code, although I don't see myself re-generating it either. So maybe changing this code is fine.]
I could see myself making an alternate constructor that takes a string as a parameter and initializes this.Url that way, but I'm not sure that's the correct approach regarding keeping loosely coupled separation of concerns. (SoC)
Any advice for this situation?
DI really just means a class wont construct it's external dependencies and will not manage the lifetime of those dependencies. Dependencies can be injected either via constructor, or via method parameter. Interfaces or abstract types are common to clarify the contract the consumer expects from its dependency, however simple types can be injected as well in some cases.
For example, a class in a library might call HttpContext.Current internally, which makes arbitrary assumptions about the application the code will be hosted in. An DI version of the library method would expect a HttpContext instance to be injected via parameter, etc.
It's not required to use interfaces -- you could use concrete types or abstract base classes. But many of the advantages of DI (such as being able to change an implementation of a dependancy) come when using interfaces.
Castle Windsor (the DI framework I know best), allows you to map objects in the IoC container to Interfaces, or to just names, which would work in your case.
Dependency Injection is a way of organizing your code. Maybe some of your confusion comes from the fact that there is not one official way to do it. It can be achieved using "regular" c# code , or by using a framework like Castle Windsor. Sometimes (often?) this involves using interfaces. No matter how it is achieved, the big picture goal of DI is usually to make your code easier to test and easier to modify later on.
If you were to inject the URL in your example via a constructor, that could be considered "manual" DI. The Wikipedia article on DI has more examples of manual vs framework DI.
I would like to answer with a focus on using interfaces in .NET applications. Polymorphism in .NET can be achieved through virtual or abstract methods, or interfaces.
In all cases, there is a method signature with no implementation at all or an implementation that can be overridden.
The 'contract' of a function (or even a property) is defined but how the method is implemented, the logical guts of the method can be different at runtime, determined by which subclass is instantiated and passed-in to the method or constructor, or set on a property (the act of 'injection').
The official .NET type design guidelines advocate using abstract base classes over interfaces since they have better options for evolving them after shipping, can include convenience overloads and are better able to self-document and communicate correct usage to implementers.
However, care must be taken not to add any logic. The temptation to do so has burned people in the past so many people use interfaces - many other people use interfaces simply because that's what the programmers sitting around them do.
It's also interesting to point out that while DI itself is rarely over-used, using a framework to perform the injection is quite often over-used to the detriment of increased complexity, a chain-reaction can take place where more and more types are needed in the container even though they are never 'switched'.
IoC frameworks should be used sparingly, usually only when you need to swap out objects at runtime, according to the environment or configuration. This usually means switching major component "seams" in the application such as the repository objects used to abstract your data layer.
For me, the real power of an IoC framework is to switch implementation in places where you have no control over creation. For example, in ASP.NET MVC, the creation of the controller class is performed by the ASP.NET framework, so injecting anything is impossible. The ASP.NET framework has some hooks that IoC frameworks can use to 'get in-between' the creation process and perform their magic.
Luke

Simple tips to reduce coupling

I have a large .NET web application. The system has projects for different intentions (e.g. CMS, Forum, eCommerce), and I have noticed a (naive) pattern of calling on another project's class. For example, the ecommerce module needs functionality to generate a file on the fly for products, and I call and reference a method in the CMS to do this, because file handling is really a job for the CMS.
Obviously (and I know why), this is bad design and a case of high coupling.
I know a few ways to handle high coupling, like restructuring the project (although I don't really think this is a robust solution), but what else can I do to reduce high coupling? Any simple tips? Also, it would be good to know why/how they reduce coupling. I use .NET 3.5 and Sql Server 2005 so things like JMS (which I keep coming across in my search for tips on this design issue), are not applicable.
Thanks
BTW,
One of the reasons I ask this is that I have read the previous questions similar to this but usually if a question that has been asked before is asked again, different tips can be learnt as different people reply to the post.
I know of dependency injection/IOC, but I am interested in the small things that can be done to reduce coupling.
How could I choose between using a static class, or an interface-derived class, or the IOC approach when deciding on how to reduce coupling? Also, I could develop a web service which could call a static class - mixing up the approaches in my solution.
The interesting thing is that in my application, I don't want it to be disjointed. So I just have a forum, ecommerce system, and any other module required, but everything has to gel into one site so each module (which is represented as a dedicated project in my Visual Studio solution) needs to know about every other module and work with it. So for example, I might have a module which handles user profiles (working with ASP.NET membership, roles, etc), but this will work with the forum module as a user on the forum will be a registered user on the site (one login throughout), and his or her profile will be coming from the user profile module. This is as opposed to seperate profiles as seen on other sites I've come across).
You should expose web services in those projects who will be needed by other projects. This is kind of the base level idea behind SOA. So, I would just create web services and consume them, which will decouple you quite a bit from how you have it now. Hope this helps.
I'd consider starting by doing an "extract interface" refactoring on the tightly coupled pieces. For example, if using the CMS as a backing store, create an interface that can store things, then create a mediator or adapter class that knows about the CMS, but isolate the logic that knows about the storage mechanism details to just that class.
Then, for testing, you can easily substitute an in-memory store or local-filesystem store that doesn't depend on the CMS being up.
Consider using techniques like dependency injection (See StructureMap, Spring.Net, NInject) to simplify instantiation if a simple factory doesn't give you the flexibility you need.
It sounds like you have a layering problem. Your assemblies should have a single dependency cycle - from least stable to most stable. That allows you to version sensibly. Generally, that cycle would be something like UI (least stable) -> Domain Core (stable) -> Data Access (most stable). You can throw in a Utilities or some infrastructre assemblies along the way, but again - they should be considered more stable than the assemblies dependent on them.
I'd guess your App.ECommerce and App.Cms assemblies are more siblings than layers - so you would not want those to depend on each other, but that doesn't mean you can't reuse functionality. For your particular scenario, you need to push the needed functionality down to a Core or Utilities assembly that both ECommerce and Cms can depend on. If it's a specific implementation that ECommerce provides, then you can push an interface or abstract base class to the Core - and have a higher layer (perhaps IoC container) wire up the concrete Cms.FileCreator class to the ECommerce.IFileCreator dependency.
Get proper abstractions in place as described by others (interfaces, etc). Program against abstractions, not concretions.
Design your classes with Dependency Injection in mind as you have described.
Use an Inversion of Control Container as the mortar between the bricks.
Unity from the Patterns & Practices team complements the Enterprise Library.
Scott Hanselman has a nice List of .NET Inversion of Control Containers.
Well, I don't know anything about .NET, but how about refactoring common code into a separate, underlaying project/layer? Loads of stuff in a web app can be done generically to suit both a CMS, a forum and eCommerce, writing to a file is a perfect example.
Another approach could be to see the forum and eCommerce as modules in a CMS, which would also make sense. Then they could safely use specified API:s of the CMS.

Categories