Skip to content

Instantly share code, notes, and snippets.

@spirit11
Created January 25, 2018 14:10
Show Gist options
  • Save spirit11/af44bc000fc643aa87b66f3545983ae6 to your computer and use it in GitHub Desktop.
Save spirit11/af44bc000fc643aa87b66f3545983ae6 to your computer and use it in GitHub Desktop.
StructureMap Func injection #ta
void Main()
{
IContainer c = new Container(x =>
{
x.For<IUsedByA>().Use<UsedByA>();
x.For<IUsedByAOther>().Use<UsedByAOther>();
x.For<IA>().Use<A0>();
});
c.GetInstance<UseIA>();
c.GetInstance<UseA0WithOverride>();
c.Configure(x => x.For<IA>().Use<A1>());
c.GetInstance<UseIA>();
c.Configure(x => x.For<IA>().Use<A2>());
try
{
c.GetInstance<UseA2>();
}
catch (StructureMapBuildPlanException e)
{
Console.WriteLine(e);
c.Configure(x => x.For<Func<int, bool, A2>>()
.Use(context => new Func<int, bool, A2>(
(i, b) => new A2(i, b, context.GetInstance<IUsedByA>())))
);
c.GetInstance<UseA2>();
}
}
interface IA { }
interface IUsedByA { }
interface IUsedByAOther { }
class UsedByA : IUsedByA { }
class UsedByAOther : IUsedByAOther { }
class ReplacementOfUsedByAOther : IUsedByAOther { }
class A0 : IA
{
public A0(IUsedByA UsedByA, IUsedByAOther UsedByA2) =>
Console.WriteLine($"IUsedByA2 is {UsedByA2.GetType().Name}");
public override string ToString() => $"A0";
}
class A1 : IA
{
public A1(IUsedByA UsedByA, int i, IUsedByAOther UsedByA2)
{
this.i = i;
}
public override string ToString() => $"A1: i = {i}";
int i;
}
class A2 : IA
{
public A2(int i, bool b, IUsedByA UsedByA)
{
this.i = i; this.b = b;
}
public override string ToString() => $"A2: i = {i} b = {b}";
int i;
bool b;
}
class UseIA
{
public UseIA(Func<int, IA> Fabric) =>
Console.WriteLine(Fabric(22));
}
class UseA2
{
public UseA2(Func<int, bool, A2> Fabric) =>
Console.WriteLine(Fabric(22, true));
}
class UseA0WithOverride
{
public UseA0WithOverride(Func<IUsedByAOther, A0> Fabric) =>
Console.WriteLine(Fabric(new ReplacementOfUsedByAOther()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment