Ninject bindings 101 - c#

Newbie Ninject question klaxxon.
I have the following classes and interfaces which describe a dependency I need to inject, and a depender into which a concrete instance of the dependency needs to be injected.
public interface IDependency { }
public class FooDependency : IDependency { }
public class Depender
{
[Inject]
public IDependency Dependency { get; set; }
public bool DependencyIsNull()
{
return Dependency == null;
}
}
I have setup my bindings with a NinjectModule instance, like so.
public class Bindings : NinjectModule
{
public override void Load()
{
Bind<IDependency>().To<FooDependency>();
}
}
And here's a unit test method which asserts that the dependency has been injected into the depender.
[TestMethod]
public void TestMethod1()
{
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
Assert.IsFalse(bar.DependencyIsNull());
}
I'm clearly doing something fundamentally wrong, as I would have expected the test to pass, but it doesn't.

Your object isn't created by your kernel. Everything needs to be created by the kernel to have dependencies injected:
// option a (recommended)
var kernel = new StandardKernel(new Bindings());
var bar = kernel.Get<IDependency>();
Assert.IsFalse(bar.DependencyIsNull());
// option b (not recommended.. but do-able)
var kernel = new StandardKernel(new Bindings());
var bar = new Depender();
kernel.Inject(bar); // injects after the fact
Assert.IsFalse(bar.DependencyIsNull());
Also, you should have that DependencyIsNull method in your interface:
public interface IDependency {
bool DependencyIsNull();
}

Related

dependency injection or factory pattern c#

I have to write a Complex calculator logic which has 4 different components to be calculated brokerage, stockprice, admin charges & other charges. Each having a different logic and formulas.
So I decided to use Unity DI. I have a ContainerFactoryClass which resolves all classes which implements IChargeCalculator interface as shown below in the TotalAnnualCostCalculator constructor.
public class TotalAnnualCostCalculator
{
private readonly IUnityContainer container;
//Constructor
public TotalAnnualCostCalculator()
{
container = ContainerFactory.InitializeContainer();
ContainerFactory.SetupContainer(container);
}
public AnnualCostCharges CalculateTotalAnnualCost(Parameters product)
{
var calculators = container.ResolveAll<ICalculator>().ToList();
// Invoke calcualtion method
Parallel.ForEach(calculators, c =>
{
return c.CalculateAnnualCost(product);
});
}
}
Container Factory class:-
public static class ContainerFactory
{
public static IUnityContainer Container { get; private set; }
public static IUnityContainer InitializeContainer()
{
var container = new UnityContainer();
RegisterDependencies(container);
return container;
}
private static void RegisterDependencies(UnityContainer container)
{
container.RegisterType<ICalculatorStrategyFactory, CalculatorStrategyFactory>("Factory");
container.RegisterType<IEffectiveAnnualCostCalculator, InvestmentManagementChargeCalculator>("IMCChargeCalculator",
new InjectionConstructor(new ResolvedParameter<ICalculatorStrategyFactory>("Factory")));
//container.RegisterType<IEffectiveAnnualCostCalculator, AdministrationChargeCalculator>("AdministrationChargeCalculator");
container.RegisterType<IEffectiveAnnualCostCalculator, AdviceChargeCalculator>("AdviceChargeCalculator");
container.RegisterType<IEffectiveAnnualCostCalculator, OtherChargeCalculator>("OtherChargeCalculator");
container.RegisterType<IInvestmentManagementChargeCalculator, LumpSumIMCCalculator>("LumpSumIMCCalculator");
container.RegisterType<IInvestmentManagementChargeCalculator, DebitOrderIMCCalculator>("DebitOrderIMCCalculator");
}
public static void SetupContainer(IUnityContainer container)
{
Container = container;
}
}
Then any API consumes my Calculator.dll by just creating an instance of TotalAnnualCostCalculator and call a method like this.
var totalCharges = calc.CalculateTotalAnnualCost(prod);
My code reviewer says its better to use Factory Pattern ,as this tightly coupled to Unity Framework.
Please advise
Indeed, don't use a DI Container at all. As Steven suggests in the comments, this seems a great fit for a Composite:
public class TotalAnnualCostCalculator : ICalculator
{
private readonly ICalculator[] calculators;
public TotalAnnualCostCalculator(params ICalculator[] calculators)
{
this.calculators = calculators;
}
public AnnualCostCharges CalculateTotalAnnualCost(Parameters product)
{
Parallel.ForEach(this.calculators, c => c.CalculateAnnualCost(product));
}
}
In the Composition Root, then, you simply new up all the ICalculator objects you'd like to use, and pass them to the constructor of TotalAnnualCostCalculator.
Register all IEffectiveAnnualCostCalculator (or what ever interface).
You just need to map the enumerable to an array of the same type.
container.RegisterType<IEnumerable<IEffectiveAnnualCostCalculator>, IEffectiveAnnualCostCalculator[]>();
Resolve with dependency injection:
private IEnumerable<IEffectiveAnnualCostCalculator> calculators;
public TotalAnnualCostCalculator(IEnumerable<IEffectiveAnnualCostCalculator> calculators)
{
this.calculators = calculators;
}
public AnnualCostCharges CalculateTotalAnnualCost(Parameters product)
{
Parallel.ForEach(this.calculators, c => c.CalculateAnnualCost(product));
}

Dependency Injection Container - How to keep available to

When creating an application with Dependency Injection and it utilizes a framework for Dependency Injection such as Unity (or Ninject).
How do you initialize registering the interfaces to the container at the beginning all together and keep them available for the application to use throughout its running lifecycle of the application?
Do you need to pass the DI Container to each method that may utilize dependency injection, or is there some way to make the container globally accessible so that you can register them all together in the beginning and access them throughout running the application without having to continually pass them, and be able to utilize them when ever needed?
Environment: Visual Studio 2015, C#, Microsoft Unity (for DI Container)
Example Code
static void Main(string[] args)
{
// Make Unity resolve the interface, providing an instance
// of TrivialPursuit class
var diContainer = new UnityContainer();
diContainer.RegisterType<IGame, TrivialPursuit>();
var gameInstance = diContainer.Resolve<IGame>();
var xotherClass = new AnotherClass();
xotherClass.TestOtherClassOtherMethod();
}
------ Another class without context of the Dependency Injection Class ------
public void TestOtherClassOtherMethod()
{
IGame gameInstance = -- -Container is Not available to resolve from in this class ---
}
Reason: I don't want to need to pass every possible type that I may need later on to each class I load up, I will just want to use the instances when I need them. The more deeper I get into classes, later as the application becomes more complex, I won't want to pass down instances for each type up from the Main() method to each class.
A Dependency Injection (DI) container is just that. A framework for facilitating DI. You don't pass the container around in order to resolve instances of objects. You just request the type you need in your classes constructor and the DI framework will inject the appropriate dependency.
Mark Seemann has written a good book on dependency injection that I would recommend.
You register everything that'll need to be resolved with the container in the composition root. That is to say when your program starts up is when everything should be registered.
Let's say we have the following code:
public class MyClass
{
public Run()
{
var dependency = new Dependency1();
dependency.DoSomething();
}
}
public class Dependency1
{
public void DoSomething()
{
var dependency = new Dependency2();
dependeny.DoSomethingElse();
}
}
public class Dependency2
{
public void DoSomethingElse()
{
}
}
This gives us the above dependency chain: MyClass -> Dependency1 -> Dependency2.
The first thing we should do is refactor the classes to take their dependencies through their constructor and rely on interfaces rather than concretions. We can't inject dependencies unless there is a place to inject them (constructor, property, etc).
Here is the refactored code:
public interface IMyClass
{
void Run();
}
public interface IDependency1
{
void DoSomething();
}
public interface IDependency2
{
void DoSomethingElse();
}
public class MyClass : IMyClass
{
public readonly IDependency1 dep;
public MyClass(IDependency1 dep)
{
this.dep = dep;
}
public void Run()
{
this.dep.DoSomething();
}
}
public class Dependency1 : IDependency1
{
public readonly IDependency2 dep;
public MyClass(IDependency2 dep)
{
this.dep = dep;
}
public void DoSomething()
{
this.dep.DoSomethingElse();
}
}
public class Dependency2 : IDependency2
{
public void DoSomethingElse()
{
}
}
You'll notice the classes now all take their dependencies through their constructors and do not new up anything. Classes should only take in dependencies that they actually need. For example, MyClass does not NEED a Dependency2 so it doesn't ask for one. It only asks for a Dependency1 because that's all it needs. Dependency1 NEEDS Dependency2, not MyClass.
Now to wire it all up WITHOUT a container we would just new it all up in the composition root:
void Main()
{
var myClass = new MyClass(new Dependency1(new Dependency2()));
}
You can see how that could get cumbersom if we had tons of classes and depdencies. That's why we use a container. It handles all the depdency graph for us. With a container we'd rewrite it as follows:
void Main()
{
// the order of our registration does not matter.
var container = new Container();
container.Register<IDependency1>.For<Dependency1>();
container.Register<IDependency2>.For<Dependency2>();
container.Register<IMyClass>.For<MyClass>();
// then we request our first object like in the first example (MyClass);
var myClass = container.Resolve<IMyClass>();
myClass.Run();
}
In the second example the container will handle wiring up all the dependencies. So we never need to pass Depedency2 to MyClass and then to Depedency1. We only need to request it in Dependency1 and the container will wire it up for us like in the first example.
So in your example we would rewrite it like so:
static void Main(string[] args)
{
var game = new UnityContainer();
game.RegisterType<IGame, TrivialPursuit>();
game.RegisterType<IAnotherClass, AnotherClass>();
game.RegisterType<IYetAnotherClass, YetAnotherClass>();
var gameInstance = game.Resolve<IGame>();
// you'll need to perform some action on gameInstance now, like gameInstance.RunGame() or whatever.
}
public class Game : IGame
{
public Game(IAnotherClass anotherClass)
{
}
}
public class AnotherClass : IAnotherClass
{
public AnotherClass(IYetAnotherClass yetAnotherClass)
{
}
}
public class YetAnotherClass : IYetAnotherClass {}
In these cases there is no need to pass the container around. You register your dependencies with the container then request them in your classes constructors. If you wish to use the container in the class WITHOUT requesting it through the constructor then you are not doing DI you are just using the container as a singleton service locator. Something that should generally be avoided.
Container as a Service Locator
This should be generally avoided but if you want to use the container as a service locator you have two options:
1) Pass the container into your classes that need it through the constructor.
You can use the above examples for wiring your classes up for DI. But instead of requesting a dependency like IDependency in the constructor you just pass the container.
public class Game : IGame
{
public Game(IContainer container)
{
var blah = container.Resolve<IBlah>();
}
}
2) Request your container through a static class:
public static class ServiceLocator
{
private static IContainer container;
public static IContainer Container
{
get
{
if (container == null)
{
container = new Container();
}
return container;
}
}
}
Register everything as normal in your composition root using the ServiceLocator class. Then to use:
public class MyClass
{
public void DoSomething()
{
var blah = ServiceLocator.Container.Resolve<IBlah>();
}
}

Ninject in WPF application: request an instance of a type

I'm developing a WPF application which has a big part of business logic and data processing.
According to idea of using IoC I've decided to use Ninject as dependency injector for this part of logic and data processing.
I've initialized the kernel of ninject and binded the interfaces with the concrete classes in the App.xaml.cs file (i.e. in the default app class). So far everything is fine.
The problem is that somewhere in my application I need two concrete instances of a class (that I do not want to pass as parameter in the constructor).
Actually what I need to do is:
var instance1 = kernel.Get<IClassName>();
The problem is that I've no access to kernel (concrete instance of the Ninject kernel).
I know that in ASP.NET MVC I could do something like
var instance1 = (IClassName)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(IClassName));
Is there something analogous that I can use?
Or am I forced to solve the problem with a service locator pattern (about which I know there is conflicting opinions)?
Since you want to use more than one dependency per class, you should look to design patterns rather than the DI container to solve your problem.
There are at least a couple of options. Here is some basic framework to setup the scenario:
public interface IPresenter
{
void Present();
}
public interface IConsumer
{
void DoSomething();
}
public class SomeConsumer : IConsumer
{
private readonly IPresenter presenter;
public SomeConsumer(IPresenter presenter)
{
if (presenter == null)
throw new ArgumentNullException("presenter");
this.presenter = presenter;
}
public void DoSomething()
{
this.presenter.Present();
}
}
You could use the composite pattern, in which you could then order the presenters in a list.
public class Presenter1 : IPresenter
{
public void Present()
{
// Do something here
}
}
public class Presenter2 : IPresenter
{
public void Present()
{
// Do something here
}
}
public class Presenter3 : IPresenter
{
public void Present()
{
// Do something here
}
}
public class CompositePresenter : IPresenter
{
private readonly IPresenter[] presenters;
public CompositePresenter(IPresenter[] presenters)
{
if (presenters == null)
throw new ArgumentNullException("presenters");
this.presenters = presenters;
}
public void Present()
{
// Do nothing except delegate the call to the nested
// instances. You may need to do some extra work to deal
// with multiple return values, like add up the values
// or decide which value works best for the scenario.
foreach (var presenter in this.presenters)
{
presenter.Present();
}
}
}
And then wire it up like:
var presenter1 = new Presenter1();
var presenter2 = new Presenter2();
var presenter3 = new Presenter3();
var compositePresenter = new CompositePresenter(new IPresenter[] {
presenter1,
presenter2,
presenter3
});
var consumer = new SomeConsumer(compositePresenter);
In Ninject, the above would look like:
var kernel = new StandardKernel();
kernel.Bind<Presenter1>().ToSelf();
kernel.Bind<Presenter2>().ToSelf();
kernel.Bind<Presenter3>().ToSelf();
kernel.Bind<IPresenter>().To<CompositePresenter>()
.WithConstructorArgument("presenters",
new IPresenter[] {
kernel.Get<Presenter1>(),
kernel.Get<Presenter2>(),
kernel.Get<Presenter3>()
});
// When SomeConsumer is injected into a constructor, its IPresenter
// dependency will be wired as shown with the new keyword example above.
Or you could use a decorator pattern:
public class Presenter1 : IPresenter
{
public Presenter1(IPresenter innerPresenter)
{
if (innerPresenter == null)
throw new ArgumentNullException("innerPresenter");
this.innerPresenter = innerPresenter;
}
public void Present()
{
// Do something here
// You could make this call conditional
this.innerPresenter.Present();
// Or do something here
}
}
public class Presenter2 : IPresenter
{
public Presenter2(IPresenter innerPresenter)
{
if (innerPresenter == null)
throw new ArgumentNullException("innerPresenter");
this.innerPresenter = innerPresenter;
}
public void Present()
{
// Do something here
// You could make this call conditional
this.innerPresenter.Present();
// Or do something here
}
}
public class Presenter3 : IPresenter
{
public Presenter3(IPresenter innerPresenter)
{
if (innerPresenter == null)
throw new ArgumentNullException("innerPresenter");
this.innerPresenter = innerPresenter;
}
public void Present()
{
// Do something here
// You could make this call conditional
this.innerPresenter.Present();
// Or do something here
}
}
public class NullPresenter : IPresenter
{
public void Present()
{
// Do nothing here - this class is a placeholder
// in case you want to expand the design later
}
}
And then wire it up like:
var nullPresenter = new NullPresenter();
var presenter3 = new Presenter3(nullPresenter);
var presenter2 = new Presenter2(presenter3);
var presenter1 = new Presenter1(presenter2);
var consumer = new SomeConsumer(presenter1);
In Ninject, the above would look like:
var kernel = new StandardKernel();
kernel.Bind<IPresenter>().To<NullPrenter>().WhenInjectedInto<Presenter3>();
kernel.Bind<IPresenter>().To<Presenter3>().WhenInjectedInto<Presenter2>();
kernel.Bind<IPresenter>().To<Presenter2>().WhenInjectedInto<Presenter1>();
kernel.Bind<IPresenter>().To<Presenter1>();
// When SomeConsumer is injected into a constructor, its IPresenter
// dependency will be wired as shown with the new keyword example above.
The advantage of using design patterns is that you end up with loosely coupled code that is totally modular, extensible, and even independent of the DI container.
How about using Ninject.Extensions.Factory for the instantiation of said dependencies?
You can inject a Func<T> and when you later call it, it will return a newly instantiated T. There's also Lazy<T> in case you just want to late-instantiate a single instance "on first usage".
Then again you can also define interface factories like:
public interface IFooFactory
{
IFoo Create();
}
with corresponding bindings:
Bind<IFooFactory>().ToFactory();
Bind<IFoo>().To<Foo>(); // add Singleton, or ToMethod binding,.. or whatever you require

MEF and ABSTRACT FACTORY

UPDATE: Should I try to handle it by DI container or it's a wrong abstraction level here?
I would like to implement ABSTRACT FACTORY using MEF (.NET 4.5).
It doesn't work for me...
The composition remains unchanged. The changes were rejected because of the following error(s):
The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) No exports were found that match the constraint:
ContractName Mef3.Factory
RequiredTypeIdentity Mef3.Factory
Resulting in: Cannot set import 'Mef3.Program._factory (ContractName="Mef3.Factory")' on part 'Mef3.Program'.
Element: Mef3.Program._factory (ContractName="Mef3.Factory") -->
Mef3.Program
Is it the right way to do it in MEF?
How can I forward id to Foo/Bar ctors?
The code:
class Program
{
static void Main(string[] args)
{
var program = new Program();
program.Run();
}
readonly CompositionContainer _container;
public Program()
{
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
_container = new CompositionContainer(catalog);
_container.ComposeParts(this);
}
[Import]
public Factory _factory;
public void Run()
{
var foo = _factory.GetInstance("foo", 123);
Console.WriteLine(foo is Foo);
}
}
[Export]
public class Factory
{
private readonly ExportFactory<Foo> _fooFactory;
private readonly ExportFactory<Bar> _barFactory;
[ImportingConstructor]
public Factory(ExportFactory<Foo> fooFactory, ExportFactory<Bar> barFactory)
{
_fooFactory = fooFactory;
_barFactory = barFactory;
}
public Base GetInstance(string name, int id)
{
switch (name)
{
case "foo":
return _fooFactory.CreateExport().Value;
case "bar":
return _barFactory.CreateExport().Value;
}
throw new ArgumentException();
}
}
public class Foo : Base
{
[ImportingConstructor]
public Foo([Import("Id")] int id)
{
}
}
public class Bar : Base
{
[ImportingConstructor]
public Bar([Import("Id")] int id)
{
}
}
[InheritedExport]
public abstract class Base
{
}
The issue looks to be caused by your [Import("Id")] on Foo and Bar. There is no export with a contract name of "Id". MEF in general doesn't allow you to pass in imports at runtime, you need to be able to satisfy the entire graph at composition time or else it will not work. If you wanted to use MEF to accomplish this particular scenario you should remove the ImportingConstructor on Foo and Bar and add a SetId method on the Base class and have your factory call it when you call GetInstance.

Moq a MEF Import?

I have a class A which has the following:
public class A {
[Import(typeof(IMyService)]
public IMyService MyService { get; set; }
public A() {
CompositionInitializer.SatisfyImports(this);
}
public void DoWork() {
//Blah
MyService.DoIt();
//Blah
}
}
And a Test to test this (seperate Dll - obviously)
[TestMethod]
public void TestDoWork() {
//Blah
DoWork();
//Assert assert
}
This fails as attempting to call 'MyService' gives me null.
I've then tried:
[ClassInitialize]
public void InitialiseClass() {
var myService = new Mock<IMyService>();
MyService = myService.Object;
}
with 'MyService' declared as:
[Export(typeof(IMyService))]
public IMyService MyService { get; set; }
But still no joy, am I missing something - is this even possible?
I'm using SL3, MEF Preview 9 and MOQ.
Any help appreciated!
Cheers
Chris
Your class should look like this:
public class A
{
private readonly IMyService _myService;
[ImportingConstructor]
public A(IMyService myService)
{
_myService = myService;
}
public void DoWork() {
//Blah
_myService.DoIt();
//Blah
}
}
And your test should look like this:
[TestMethod]
public void DoWork_invokes_IMyService_DoIt()
{
// arrange mock and system under test
var myService = new Mock<IMyService>();
var a = new A(myService.Object);
// act
a.DoWork();
// assert that DoIt() was invoked
myService.Verify(x => x.DoIt());
}
The fact that you use MEF should not be important in unit tests. MEF only comes into play when wiring many components together, which is exactly the opposite of what happens in a unit test. A unit test is by definition a test of a component in isolation.
Edit: if you prefer property injection, then your class doesn't need a constructor and the arrange part in your unit test should look like this instead:
var myService = new Mock<IMyService>();
var a = new A();
a.MyService = myService.Object;
Where you've added [Export] to your IMyService instance, have you actually added that to the composition container? If not, it won't take part in composition. To add a mocked object to the container, do the following:
container.ComposeExportedValue<IMyService>(mock.Object);
Or just:
container.ComposeExportedValue(mock.Object); // type inference.
Doing this before you've created an instance of A will enable it to be composed inside your A instance.
You shouldn't be firing up MEF in your unit tests. Composition is way beyond unit test's scope, not dissimilar to an IoC container.
Insted, you should inject required dependencies manually:
[TestClass]
public class ATest {
Mock<IMyService> myService ;
[TestInitialize]
public void InitialiseClass() {
myService = new Mock<IMyService>();
}
[TestMethod]
public void DoWorkShouldCallDoIt {
A a = new A();
a.MyService = myService.Object;
a.DoWork();
myService.Verify(m=>m.DoIt(), Times.Once());
}
}

Categories

Resources