Created
April 11, 2016 18:25
-
-
Save dealproc/9a32982917b19915377f6067ff2ab364 to your computer and use it in GitHub Desktop.
Keyed instances of object(s)
This file contains hidden or 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 System.ComponentModel.Composition; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Reflection; | |
using Autofac; | |
namespace AFMetadata { | |
class Program { | |
public const string CONSOLE = "4ACD5288-840A-40A8-81D1-8244BDD60D57"; | |
public const string TRACE = "EFF42F1C-CD85-41F9-8453-E73DF3B24393"; | |
static IContainer _container; | |
static void Main(string[] args) { | |
BuildContainer(); | |
var sut = _container.Resolve<LogSomeText>(); | |
sut.Log(CONSOLE, "console text"); | |
sut.Log(TRACE, "trace text"); | |
DisposeContainer(); | |
Console.ReadLine(); | |
} | |
static void BuildContainer() { | |
var cb = new ContainerBuilder(); | |
cb.RegisterType<LogSomeText>().AsSelf(); | |
cb.RegisterAssemblyTypes(typeof(Program).Assembly) | |
.Where(t => t.IsAssignableTo<ILog>() && t.GetCustomAttribute<LogIdAttribute>() != null) | |
.Keyed<ILog>(t => t.GetCustomAttribute<LogIdAttribute>().Id); | |
cb.Register<Func<string, ILog>>(ctx => { | |
var c = ctx.Resolve<IComponentContext>(); | |
return key => c.ResolveKeyed<ILog>(key); | |
}).AsSelf(); | |
_container = cb.Build(); | |
} | |
static void DisposeContainer() { | |
if (_container != null) { | |
_container.Dispose(); | |
_container = null; | |
} | |
} | |
} | |
class LogSomeText { | |
readonly Func<string, ILog> _sinkFactory; | |
public LogSomeText(Func<string, ILog> sinkFactory) { | |
_sinkFactory = sinkFactory; | |
} | |
public void Log(string sinkKey, string info) { | |
_sinkFactory.Invoke(sinkKey).Log(info); | |
} | |
} | |
interface ILog { | |
bool Log(string data); | |
} | |
[LogId(Program.CONSOLE)] | |
class ConsoleLogger : ILog { | |
public bool Log(string data) { | |
Console.WriteLine(data); | |
return true; | |
} | |
} | |
[LogId(Program.TRACE)] | |
class TraceLog : ILog { | |
public bool Log(string data) { | |
Trace.WriteLine(data); | |
return true; | |
} | |
} | |
[MetadataAttribute] | |
class LogIdAttribute : Attribute { | |
public string Id { get; private set; } | |
public LogIdAttribute(string guid) { | |
Id = guid; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment