Created
January 9, 2019 10:52
-
-
Save tkirill/f2cbe320d33e0ff77296ae33b430f84a to your computer and use it in GitHub Desktop.
Possible explicit args for IContext.GetInstance
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
using System; | |
using StructureMap; | |
namespace StructureMapExplicitArgsExample | |
{ | |
class Soldier | |
{ | |
private Gun _gun; | |
public Soldier(Gun gun) => _gun = gun; | |
} | |
class Gun | |
{ | |
public Gun(IAmmo ammo) => Console.WriteLine(ammo.GetType()); | |
} | |
interface IAmmo{} | |
class InfiniteAmmo : IAmmo{} | |
class LimitedAmmo : IAmmo{} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var container = new Container(); | |
// Explicit args works great | |
container.With<IAmmo>(new InfiniteAmmo()).GetInstance<Soldier>(); | |
container.With<IAmmo>(new LimitedAmmo()).GetInstance<Soldier>(); | |
} | |
} | |
interface IFoo {} | |
class Foo : IFoo | |
{ | |
public Foo(Soldier soldier) {} | |
} | |
class MyRegistry : Registry | |
{ | |
public MyRegistry() | |
{ | |
// Want to register Foo with Soldier created with InfiniteAmmo | |
// Any other solutions except manually call .Ctor for all dependencies down the tree? | |
For<IFoo>().Use("hello", context => | |
{ | |
// Would be nice to use explicit args here | |
var soldier = context.With<IAmmo>(new InfiniteAmmo()).GetInstance<Soldier>(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment