Created
November 4, 2015 09:59
-
-
Save seesharper/50c7d9ae76c2bcae383b to your computer and use it in GitHub Desktop.
Using Lazy<T,TMetadata>
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.Collections.Generic; | |
| using System.Linq; | |
| using System.Reflection; | |
| using LightInject; | |
| namespace ConsoleApplication2 | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var container = new ServiceContainer(); | |
| container.Register<Bar>(); | |
| var concreteFooTypes = | |
| typeof (Program).Assembly.GetTypes() | |
| .Where(t => typeof (IFoo).IsAssignableFrom(t) && t.IsDefined(typeof (MyMetadataAttribute), true)).ToArray(); | |
| foreach (var concreteFooType in concreteFooTypes) | |
| { | |
| string serviceName = concreteFooType.AssemblyQualifiedName; | |
| container.Register(typeof(IFoo), concreteFooType, serviceName); | |
| IMyMetadata metadata = (IMyMetadata)concreteFooType.GetCustomAttribute(typeof (MyMetadataAttribute), true); | |
| container.Register<Lazy<IFoo,IMyMetadata>>(factory => new Lazy<IFoo, IMyMetadata>(() => factory.GetInstance<IFoo>(serviceName), metadata), serviceName); | |
| } | |
| container.GetInstance<Bar>(); | |
| Console.ReadKey(); | |
| } | |
| } | |
| public interface IMyMetadata | |
| { | |
| bool SupportsFeature { get; set; } | |
| } | |
| public class MyMetadataAttribute : Attribute, IMyMetadata | |
| { | |
| public bool SupportsFeature { get; set; } | |
| } | |
| public interface IFoo | |
| { | |
| } | |
| [MyMetadata(SupportsFeature = true)] | |
| public class Foo : IFoo | |
| { | |
| } | |
| [MyMetadata(SupportsFeature = false)] | |
| public class AnotherFoo : IFoo | |
| { | |
| } | |
| public class Bar | |
| { | |
| public Bar(IEnumerable<Lazy<IFoo, IMyMetadata>> laziesWithMetadata) | |
| { | |
| foreach (var lazyWithMetadata in laziesWithMetadata) | |
| { | |
| Console.WriteLine(lazyWithMetadata.Metadata.SupportsFeature); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment