Last active
December 28, 2015 05:39
-
-
Save bentayloruk/7450996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//install-package Autofac. | |
using System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.Linq; | |
using Autofac; | |
namespace Funcofac | |
{ | |
class Program | |
{ | |
/// <summary> | |
/// Class A does something awesome with some injected functions. | |
/// </summary> | |
class A | |
{ | |
readonly IEnumerable<Func<int, string>> _someFuncsYo; | |
public A(IEnumerable<Func<int,string>> someFuncsYo) | |
{ | |
if (someFuncsYo == null) throw new ArgumentNullException("someFuncsYo"); | |
_someFuncsYo = someFuncsYo; | |
} | |
public string DoIntStringMadness(int i) | |
{ | |
//This is not xPlat ;) | |
return "Funcs out:\n" + String.Join("\n", _someFuncsYo.Select(f => f(i))); | |
} | |
} | |
/// <summary> | |
/// Class B has some useful instance and static methods. | |
/// </summary> | |
class B | |
{ | |
readonly int _i; | |
public B(int i) | |
{ | |
_i = i; | |
} | |
public string AwesomeInstanceMethod(int i) | |
{ | |
return i.ToString(CultureInfo.InvariantCulture) + _i; | |
} | |
public static string AwesomeStaticMethod(int i) | |
{ | |
return i.ToString(CultureInfo.InvariantCulture) + " I'm like totally static."; | |
} | |
} | |
//Let's get down to work! | |
static void Main(string[] args) | |
{ | |
//Build my container. | |
var container = BuildContainer(); | |
//Resolve the composition root. | |
var a = container.Resolve<A>(); | |
//Did something awesome without interfaces. | |
var intStringMadness = a.DoIntStringMadness(2013); | |
//Funcs out: | |
//2013 I'm like totally static. | |
//201352 | |
//201342 | |
} | |
static IContainer BuildContainer() | |
{ | |
var containerBuilder = new ContainerBuilder(); | |
containerBuilder.Register(c => (Func<int, string>) (i => new B(42).AwesomeInstanceMethod(i))); | |
containerBuilder.Register(c => (Func<int, string>)(i => new B(52).AwesomeInstanceMethod(i))); | |
containerBuilder.Register<Func<int, string>>(c => B.AwesomeStaticMethod); | |
containerBuilder.RegisterType<A>(); | |
return containerBuilder.Build(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment