Created
December 8, 2016 17:01
-
-
Save scottcowan/91deb5e15a686d767ab29cb91d409ec9 to your computer and use it in GitHub Desktop.
change your logger for an instance and it's children
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 ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var container = new Container(_ => | |
{ | |
_.For<IWorker1>().Use<Worker1>(); | |
_.For<IWorker2>().Use<Worker2>(); | |
_.For<IRunAll>().Use<RunAll>(); | |
_.For<ILog>().Use<Logger>(); | |
}); | |
container.GetInstance<IRunAll>().Run(); | |
} | |
} | |
public interface IRunAll | |
{ | |
void Run(); | |
} | |
public class RunAll : IRunAll | |
{ | |
private readonly IWorker1 _worker1; | |
private readonly IWorker2 _worker2; | |
private readonly IContainer _container; | |
public RunAll(IWorker1 worker1, IWorker2 worker2, IContainer container) | |
{ | |
_worker1 = worker1; | |
_worker2 = worker2; | |
_container = container; | |
} | |
public void Run() | |
{ | |
using (var nested = _container.GetNestedContainer()) | |
{ | |
nested.Configure(_ => { _.For<ILog>().Use<Logger1>(); }); | |
_worker1.Run(); | |
} | |
using (var nested = _container.GetNestedContainer()) | |
{ | |
nested.Configure(_ => { _.For<ILog>().Use<Logger2>(); }); | |
_worker2.Run(); | |
} | |
} | |
} | |
public interface IWorker | |
{ | |
void Run(); | |
} | |
public interface IWorker1 : IWorker { } | |
public interface IWorker2 : IWorker { } | |
public class Worker1 : IWorker1 | |
{ | |
private readonly ILog _log; | |
public Worker1(ILog log) | |
{ | |
_log = log; | |
} | |
public void Run() | |
{ | |
_log.Info("worker 1"); | |
} | |
} | |
public class Worker2 : IWorker2 | |
{ | |
private readonly ILog _log; | |
public Worker2(ILog log) | |
{ | |
_log = log; | |
} | |
public void Run() | |
{ | |
_log.Info("worker 2"); | |
} | |
} | |
public interface ILog | |
{ | |
void Info(string message); | |
} | |
public class Logger : ILog | |
{ | |
public void Info(string message) | |
{ | |
Console.WriteLine(message); | |
} | |
} | |
public class Logger1 : ILog | |
{ | |
public void Info(string message) | |
{ | |
Console.WriteLine($"[1] {message}"); | |
} | |
} | |
public class Logger2 : ILog | |
{ | |
public void Info(string message) | |
{ | |
Console.WriteLine($"[2] {message}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment