Is dependency injection useful in C++ - c#

C# uses Dependency Injection (DI) a lot to have a lossless and testable platform. For this, I need an interface and maybe a DI or Inversion of Control (IoC) container for resolving my instances.
But how do you do this in C++? I've read a little bit about this, and it seems that dependency injection in C++ isn't as big a topic as in C#. In C++ you use a reference to an object - this is the way to use DI in C++, right?
If my theory with references are correct, is there something like a container where I can resolve all the references? In C# I have a "bad class/bad project/assembly" which registers all my instances into a static container at the program start. Then, in every class, I'm able to instance the static container and can resolving a specific instance, is this possible in C++?
Are you using Dependency Injection (or whatever it is called) in C++? If yes, how you're use it? Are there similarities to C#?

For this, I need an interface and maybe a container for resolving my instances. But how you do this in C++?
In the same way. The difference is that where you "program to an interface" in C#, you "program to a base class" in C++. Additionally, you have extra tools in C++ that you do not have in C# (for example, policy-based templates implement dependency injection chosen at compilation time).
In C++ you're use a reference to an object, this is the way to use DI in C++, right?
No; this is not the way to use DI, this is a way to use DI in C++.
Also consider:
use a pointer to an object (or smart pointer, depending on the case)
use a template argument for a policy (for an example, see std::default_delete use in smart pointers)
use lambda calcullus with injected functors/predicates.
In C# I've a "bad class/bad project/assembly" which register all my instance into a static container at the program start.
If I understand correctly, you set all your data in this static container and use it all over the application. If this is the case, then you do not use dependency injection correctly, because this breaks Demeter's Law.
is this possible in C++?
Yes, it is perfectly possible (but you shouldn't do it, due to it breaking Demeter's law). Have a look at boost::any (this will allow you to store heterogenous objects in a container, similar to storing objects by object reference in C#).
Are you using dependency injection or whatever it is called in C++?
Yes (and it is called dependency injection :) ).
If yes, how you're use it?
As I described above (policy template arguments, injected functors and predicates as reusable components, injecting objects by reference, pointer smart pointer or value).

With C++11 as a project limit I ended up rolling my own. I loosely based it on .NET Ninject API without the Reflection ofcourse.
ServiceLocator
Note, although its called ServiceLocator (since it does not do Dependancy Injection itself) if you use lambda function bindings and preferably ServiceLocator::Module classes you get Injection (not reflection based) and it works really really well (IMO)
#include <iostream>
#include <vector>
#include "ServiceLocator.hpp"
template <class T>
using sptr = std::shared_ptr<T>;
// Some plain interfaces
class IFood {
public:
virtual std::string name() = 0;
};
class IAnimal {
public:
virtual void eatFavouriteFood() = 0;
};
// Concrete classes which implement our interfaces, these 2 have no dependancies
class Banana : public IFood {
public:
std::string name() override {
return "Banana";
}
};
class Pizza : public IFood {
public:
std::string name() override {
return "Pizza";
}
};
// Monkey requires a favourite food, note it is not dependant on ServiceLocator
class Monkey : public IAnimal {
private:
sptr<IFood> _food;
public:
Monkey(sptr<IFood> food) : _food(food) {
}
void eatFavouriteFood() override {
std::cout << "Monkey eats " << _food->name() << "\n";
}
};
// Human requires a favourite food, note it is not dependant on ServiceLocator
class Human : public IAnimal {
private:
sptr<IFood> _food;
public:
Human(sptr<IFood> food) : _food(food) {
}
void eatFavouriteFood() override {
std::cout << "Human eats " << _food->name() << "\n";
}
};
/* The SLModule classes are ServiceLocator aware, and they are also intimate with the concrete classes they bind to
and so know what dependancies are required to create instances */
class FoodSLModule : public ServiceLocator::Module {
public:
void load() override {
bind<IFood>("Monkey").to<Banana>([] (SLContext_sptr slc) {
return new Banana();
});
bind<IFood>("Human").to<Pizza>([] (SLContext_sptr slc) {
return new Pizza();
});
}
};
class AnimalsSLModule : public ServiceLocator::Module {
public:
void load() override {
bind<IAnimal>("Human").to<Human>([] (SLContext_sptr slc) {
return new Human(slc->resolve<IFood>("Human"));
});
bind<IAnimal>("Monkey").to<Monkey>([] (SLContext_sptr slc) {
return new Monkey(slc->resolve<IFood>("Monkey"));
});
}
};
int main(int argc, const char * argv[]) {
auto sl = ServiceLocator::create();
sl->modules()
.add<FoodSLModule>()
.add<AnimalsSLModule>();
auto slc = sl->getContext();
std::vector<sptr<IAnimal>> animals;
slc->resolveAll<IAnimal>(&animals);
for(auto animal : animals) {
animal->eatFavouriteFood();
}
return 0;
}

Using dependency injection is quite straightforward in C++. Just define an interface (a pure abstract base class) that you use as reference or pointer (or smart pointer) argument to the constructor or init function of the class you want to dependency inject into.
Then, in the unit test, inject a mock object (an instance of a class inheriting from the abstract interface class), and in real code, inject an instance of the real class (also inheriting from the same interface class).
Easy-peasy.

Yes, dependency injection is useful in C++ as well. There is no reason why it shouldn´t be, because it doesn´t require a specific language or syntax, but just an object-oriented class architecture (at least this is probably the most usual case).
While in C# there are only "pointers" to dynamically allocated objects, C++ has multiple variants, like "normal" local variables, multiple kind of pointers, references... additionally the concept of move semantics is very relevant to this.
In C++ you're use a reference to an object, this is the way to use DI
in C++, right?
Not only. You can use whatever you want as long you can pass something to a class method and this something will exist as long as the class object does. All of the three possibilites above can do that (each of them with certain restrictions)
is there something like a container were I can resolve all this
references? In C# I've a "bad class/bad project/assembly" which
register all my instance into a static container
Maybe you´re missing the point of dependeny injection. It´s not the same as a bunch of "global" variables. But yes, of course this is possible in C++ too. There are classes, there is static, and that´s everything needed.

If my theory with references are correct, is there something like a container where I can resolve all the references? In C# I have a "bad class/bad project/assembly" which registers all my instances into a static container at the program start. Then, in every class, I'm able to instance the static container and can resolving a specific instance, is this possible in C++?
That's not how DI is supposed to be used, you don't pass your container to all your "consumer" class. In a well designed application you just do few resolve in the entry point and that's it. Most of the time the need for a "resolve" can be replaced by the use of a factory which will be registered then injected.
You'll have a lot of trouble testing code depending on a static class. I would recommend if you really want to inject your container in your client class to at least instance and inject it, static dependencies are hell, would be easier to mock for unit testing.

Related

Access interface methods without referring the class

Say I have an Interface like this in a project called "Interface":
public interface TestInterface
{
string Operation();
}
and class which implements it. This class is located in another project "Class":
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
My client does something like this (which is again in a different project "Client"):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
My question is related to this line:
TestInterface i = new TestClass();
By adding this line, I'm actually forced to add a references to both "Interface" as well as "Class" projects from my "Client" project. So why all this fuss? Can't I directly refer to the "Class" without keeping the "Interface" in between? Is there any way to access the methods via Interface only (without making a reference to the implementation Class)? Am I missing something here?
Is there any way to access the methods via Interface only
Yes, there is. You can dynamically load an assembly with TestClass without referencing it, create its instance via Activator.CreateInstance and cast it to interface type:
var assembly = Assembly.Load(...);
var typeFromAssembly = assembly.GetTypes()...;
var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:
[Import]
private TestInterface myInterfaceField;
or:
var myInterfaceVar = compositionContainer.GetExportedValue<TestInterface>();
Depending of the way you prefer, you may ask more concrete question.
In that particular sample, there is no advantage.
But imagine a method:
public void Foo(ITestInterface handler)
{
handler.Operation();
}
Now, Foo operates only on the interface and it doesn't care what concrete class implements this interface. You could now call Foo with an instance of TestClass or with TestClass2, which could be defined in a different assembly.
you can achieve the behavior you have described via using IOC.
Unity is a dependency injection container which allows to create instances without manually creating instances.
For instance, if you were to register your class and interface to unity, you would directly use the interface;
TestInterface i = Container.Resolve<TestInterface>();
To make your code completely independent from implementation of TestInterface use Dependency Inversion. This could be achieved by some Dependency Injection framework.
E.g. with Unity you can configure implementation via xml
<register type="TestInterface"
mapTo="Foo.Bar.TestClass, Foo.Bar" />
And your code will depend only on Unity (no references to implementation):
TestInterface i = Container.Resolve<TestInterface>();
You have interface so that your app can have plug in's..
So basically you share your Interface dll to anyone who wants to make a plugin app for your app and then you can cast that new plugin class to the interface and invoke methods on it..
If you dont cast the class to the interface,how on earth are you going to make the plugin class work for your app..

Mocking out a local variable in C#

I have a C# class which instantiates on its own a NetworkCommunicator class. I'd like to mock out the NetworkCommunicator class for my unit test, and replace it with a pretty simple stub.
But the NetworkCommunicator is never passed as a parameter. It's created by the class being tested.
In Ruby, this is easy to mock out. In Java, this is why you need Dependency Injection, which is too heavy for this project. Is there a simple way to mock this out in C#, perhaps using Moq or something similar?
You mentioned that DI is too heavyweight for this project, why not try some Truck Driver's DI, thus:
public interface IDependency
{
void DoSomeStuff();
}
public class ClassUnderTest
{
private IDependency _dependency;
public ClassUnderTest(IDependency dependency)
{
_dependency = dependency;
}
public ClassUnderTest() : this(new Dependency())
{}
public void ImportantStuff()
{
_dependency.DoSomeStuff();
}
}
Using this constructor chaining technique, you can now mock the IDependency all you want, without worrying about hooking up DI or IoC.
Create a "TestClass" that inherits from your class under test.
Override that parameter with a mocked instance
Create a property on the class under test that returns the new instance
public class ClassUnderTest {
public string MethodYouAreTesting(int someInput) {
var networkCommunicator = GetNetworkCommunicator();
// Do some stuff that I might want to test
return "foo";
}
public virtual NetworkCommunicator GetNetworkCommunicator {
return new NetworkCommunicator();
}
}
[TestFixture]
public class ClassUnderTestTests {
public void GivenSomeCondition_MethodYouAreTesting_ReturnsFooString() {
var classToTest = new TestClassUnderTest();
var result = classToTest.MethodYouAreTesting(1);
Assert.That(result, Is.EqualTo("foo");
}
}
public class TestClassUnderTest : ClassUnderTest {
public override GetNetworkCommunicator {
return MockedNetworkCommunicator;
}
}
I read of this technique this in the "Art of Unit Testing" and use it frequently when refactoring to full DI doesn't make sense or when the class I'm testing isn't something I can change.
Hope this helps.
You should refactor your code and pass dependencies in. You can also use typemock as easier to use alternative to fakes in Visual Studio 2012.
There's the built-in Fakes system, pretty well described at http://msdn.microsoft.com/en-us/library/hh549175.aspx
If that is too heavy-weight for your use case you might find the PrivateObject class more useful.
I have a C# class which instantiates on its own a NetworkCommunicator class.
As you noticed, this is a show stopper in C# when you want to mock this thing out. Solution is simple, and depends on context/purpose of the instantiated class:
inject it as a dependency if it's reusable component
provide it via factory if it's something that should be created every time when demand comes in
Either way, you'll need DI (factory from the second example is naturally injected too).
In Java, this is why you need Dependency Injection, which is too heavy for this project.
Is dependency injection too heavy? DI is design pattern, it's only too heavy when used when it's not really needed. Your question clearly shows you need it. Perhaps you meant that DI container is too heavy for your project? This might be true, as depending on project's complexity, you should choose appropriate way to apply DI.
I'd like to raise one more point to be aware of when applying solution like the one proposed in Greg Smith's answer. Essentially, your API ends up with constructors:
public TestedClass() : this(new Dependency()) ...
public TestedClass(IDependency) ...
As appealing as it might be at first glance, when long-term perspective is taken into account, several issues start to emerge:
does TestedClass must have IDependency or can it do fine without it?
what default (parameterless constructor) defaults to (implementation detail-level knowledge is required to use it properly)?
it creates tightly coupled components (TestedClass assembly will possibly have to reference other assembly - Dependency's assembly, even though it might not be relevant to it anyhow)
This is an anti-pattern going under different names, e.g. Bastard Injection. Of course, some of those problems might be mitigated (like making constructor protected/internal or having default implementation in the same assembly), but the anti-pattern and its long-term consequences remain. Also note that it's by no means more simple, faster or less code than regular DI.
You'll have to ask yourself what's less heavy - applying proper DI, or going you ways around with anti-patterns and/or 3rd party frameworks (MS Fakes).

What's the best way to implement a dynamic proxy in C#?

I've got a need to create a dynamic proxy in C#. I want this class to wrap another class, and take on it's public interface, forwarding calls for those functions:
class MyRootClass
{
public virtual void Foo()
{
Console.Out.WriteLine("Foo!");
}
}
interface ISecondaryInterface
{
void Bar();
}
class Wrapper<T> : ISecondaryInterface where T: MyRootClass
{
public Wrapper(T otherObj)
{
}
public void Bar()
{
Console.Out.WriteLine("Bar!");
}
}
Here's how I want to use it:
Wrapper<MyRootClass> wrappedObj = new Wrapper<MyRootClass>(new MyRootClass());
wrappedObj.Bar();
wrappedObj.Foo();
to produce:
Bar!
Foo!
Any ideas?
What's the easiest way to do this?
What's the best way to do this?
Thanks so much.
UPDATE
I tried following Wernight's recommendation and implement this using C# 4.0 dynamic proxies. Unfortunately, I'm still stuck. The point of the proxy is to mimick the other interface which is (normally, usually) expected. Using DynamicObject requires me to change all the clients of this to use 'dynamic' instead of 'ISecondaryInterface'.
Is there a way to get a proxy object, such that when it wraps an A, it advertises (statically?) that it supports A's interface; and when it wraps a B, it advertises that is supports B's interface?
UPDATE 2
For example:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}
.NET 4 DynamicObject can help you achieving that.
Earlier .NET framework can use:
Aspect#
Encase AOP
Spring.NET
Aspect.NET
AspectDNG
Dynamic Proxy
Compose*
Loom.NET
PostSharp
Each of these frameworks make use of a number
techniques to the injection of code
both before and after execution of a
method. These generally fall into 4
categories.
MSIL injection – Here we inject MSIL code into the body of the
method being executed. (Post sharp)
Runtime dynamic injection – Using techniques such as reflection we
invoke methods dynamically.
Type builder injection – Related to runtime injection, we create a type based on
the type we wish to proxy and then marshal requests through this type. (Dynamic Proxy)
Container injection – Requests pass through a container
which invokes code before and after our method being executed.
See the full article.
I know that Castle Project's Dynamic Proxy is often used (like in Moq just to name one large project).
REPLY TO UPDATED TOPIC
What you wrote will not compile. Dynamic proxies are runtime generated code, so you'll have to create a concrete instance of the class you're proxying some way or another. May be you're looking to do AOP (aspect-oriented programming).
class MySecretProxy<T> : DynamicObject, T where T : new()
{
private T _instance = new T();
public override void TryInvokeMember(...) { ... }
}
MySecretProxy<Bar> bar;
Have you looked at the Castle project's DynamicProxy? It may provide what you're ultimately trying to achieve. See http://www.castleproject.org/dynamicproxy/index.html
It's also open source so you could even fork it if required.
You can do this with RealProxy if the target Type is an interface or derives from MarshalByRefObject.
You may want to look at linfu which contains a dynamic proxy mechanism.
I know the proxies that used by nhibernate for lazy loading
Castle
Linfu
Spring ByteCode

C#/.Net enforcing (or just 'hint to fellow developers') that a class method is only supposed to be called from another specific class?

I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.

Why classes tend to be defined as interface nowadays?

These 2-3 last years, many projects I see, like Cuyahoga open source C# CMS, tends to define persistent and non persistent classes as Interface. Why? Is there a good reason? TDD? Mocking? A design pattern? ...
The main reason is that this makes techniques like dependency injection easier. This in turn allows for more flexibility in the software and easier reuse and recombination of existing code. Examples for where this is useful include the various forms of unit testing (as you mentioned), but also most other forms of "regular" code reuse.
A simple example:
Say you have a method that calculates emplyoee salaries. As part of its signature, it accepts an object that calculates their benefits, say an instance of BenefitCalculator:
calculateSalary(... BenefitCalculator bc, ...)
Originally, your design has only one class BenefitCalculator. But later, it turns out that you need more than one class, e.g. because different parts of the software are supposed to use different algorithms (maybe to support different countries, or because the algorithm is supposed to be user-configurable...). In that case, rather than bloat the existing implementation of BenefitCalculator, it makes sense to create new class(es), e.g. BenefitCalculatorFrance, or BenefitCalculatorSimple etc.
Now if you use the signature
calculateSalary(... BenefitCalculator bc, ...)
, you are kind of screwed, because you cannot supply different implementations. If however you use
calculateSalary(... IBenefitCalculator
bc, ...)
you can just have all classes implement the interface.
This is actually just a special case of "loose coupling": Demand as little as possible from other parts of the code. In this case, don't demand a certain class; instead just demand that certain methods exist, which is just what an Interface does.
First of all, you can't define a class as an interface. Your class implements an interface.
Interfaces are used as one way to enable polymorphic behavior. Each class that implements the interface is free to specify its own implementation of the methods defined in the interface. Take the following for example:
You are writing banking software. Your task is to write a Transaction Processor. Now, you know you need to handle different kinds of Transactions (Deposits, Withdraws, Transfers). You could write code that looks like:
public class TransactionProcessor
{
public void ProcessDeposit( // Process Deposit );
public void ProcessWithdraw( // Process Withdraw );
public void ProcessTransfer( // Process Transfer );
}
And then every time somebody adds a new Transaction type, you have to modify your class. Or, you could:
public interface ITransaction { void Process(); }
public class TransactionProcessor
{
public void ProccessTransaction(ITransaction t) { t.Process(); }
}
Now you don't need to modify your code to Process a new type of transaction. You just need people to create their own class that implements ITransaction and your class will "just handle it".
This allows you to swap implementations of an interface depending on your needs. It also enables things like Dependency Injection and Mocking Frameworks for Unit Testing.
In general though, it really is just another way to make your code more flexible.
Interfaces have the advantage that they make you independent from the implementation, which is a good thing.
During last years IoC containers become quite popular with developers.
For example, Unity Container from Microsoft Practices. So, at the start of your application you can register concrete classes which implement interfaces, and then, for example, all classes which contain these interfaces in their constructors, or their properties marked with [Dependency] attribute will be filled, when instancing objects via Unity container's resolve. Its quite useful in the apps with complicated dependencies, when one interface can be implemented in three different classed.
And all these things can't be achieved without usage of interfaces.
At a really boring level interfaces can also help make for a faster compile.
public class A {
B b;
}
public class B {
public int getCount() {
return 10;
}
}
In this case every time internal changes to B are made, the compiler needs to re-evaluate A to determine if it needs to be recompiled.
Instead we use interfaces:
class A {
IB b;
}
interface IB {
int getCount();
}
class B : IB {
public int getCount() {
return 10;
}
}
In this case A only depends on IB. No change to B requires any consideration of A at compile time.
At scale this effect on short circuiting dependency evaluation can significantly speed up compilation of large code bases. It is particularly powerful when there are a lot of classes depending on a single class that changes a lot.
Clearly this compile time benefit only works if the classes have no static dependency on the implementation classes. Doing the following would totally defeat this benefit:
class A {
IB b = new B();
}
This is where Dependency Injection comes in. The DI container would construct a B and provide it to A as an IB so A doesn't need to have the static dependency.

Categories

Resources