Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Ninject;
- using Ninject.Activation;
- using Ninject.Extensions.Factory;
- using Ninject.Planning.Targets;
- using System;
- using System.Linq;
- namespace DI
- {
- public class D1
- {
- public string A { get; }
- public D1(string a)
- {
- A = a;
- }
- }
- public class D2
- {
- public D1 D1 { get; }
- public string B { get; }
- public D2(D1 d1, string b)
- {
- D1 = d1;
- B = b;
- }
- }
- public class D3
- {
- public D4 D4 { get; }
- public D3(D4 d4)
- {
- D4 = d4;
- }
- }
- public class D4
- {
- public D1 D1 { get; }
- public D4(D1 d1)
- {
- D1 = d1;
- }
- }
- public class Algorithm
- {
- public D1 D1 { get; }
- public D2 D2 { get; }
- public D3 D3 { get; }
- public Algorithm(D1 d1, D2 d2, D3 d3)
- {
- D1 = d1;
- D2 = d2;
- D3 = d3;
- }
- }
- public interface IAlgorithmFactory
- {
- Algorithm Create((string a, string b) input);
- }
- class Program
- {
- static void Main(string[] args)
- {
- var a = "valueOfA";
- var b = "valueOfB";
- var algorithm = GetAlgorithmUsingNInject(a, b);
- // Conditions
- Console.WriteLine(algorithm.D1.A == a);
- Console.WriteLine(algorithm.D2.B == b);
- Console.WriteLine(algorithm.D2.D1 == algorithm.D1);
- Console.WriteLine(algorithm.D3.D4.D1 == algorithm.D1);
- }
- private static Algorithm GetAlgorithmUsingPureDi(string a, string b)
- {
- var d1 = new D1(a);
- var d2 = new D2(d1, b);
- var d4 = new D4(d1);
- var d3 = new D3(d4);
- var algorithm = new Algorithm(d1, d2, d3);
- return algorithm;
- }
- private static Algorithm GetAlgorithmUsingNInject(string a, string b)
- {
- var scope = new object();
- var kernel = new StandardKernel(new FuncModule());
- kernel.Bind<Algorithm>().ToSelf();
- kernel.Bind<IAlgorithmFactory>().ToFactory();
- kernel.Bind<D1>().ToSelf().InScope(x => scope).WithConstructorArgument("a", ArgumentValueCallback(tuple => tuple.a));
- kernel.Bind<D2>().ToSelf().InScope(x => scope).WithConstructorArgument("b", ArgumentValueCallback(tuple => tuple.b));
- kernel.Bind<D3>().ToSelf().InScope(x => scope);
- kernel.Bind<D4>().ToSelf().InScope(x => scope);
- return kernel.Get<IAlgorithmFactory>().Create((a,b));
- }
- private static Func<IContext, ITarget, object> ArgumentValueCallback(Func<(string a, string b), object> extractionFunction)
- {
- return (context, target) =>
- {
- // Find the requested parameter with the name "input"
- var inputParameter = context
- .Parameters
- .Where(p => p.Name == "input")
- .Single();
- // Extract the input tuple (we know it should be (string, string))
- var input = (ValueTuple<string,string>)inputParameter.GetValue(context, target);
- // Extract the value
- return extractionFunction(input);
- };
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement