Last active
June 22, 2021 07:47
-
-
Save dadhi/cbcf09d94d7eddd161b2 to your computer and use it in GitHub Desktop.
Example of DryIoc usage for .NET Week column in http://blogs.msdn.com/b/dotnet/
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 DryIoc.MefAttributedModel; | |
using DryIocAttributes; | |
using NUnit.Framework; | |
namespace DryIoc.Examples | |
{ | |
[TestFixture] | |
public class DotnetWeekBlogExample | |
{ | |
[Test] | |
public void Test() | |
{ | |
var container = new Container().WithMefAttributedModel(); | |
container.RegisterExports(typeof(Foo<,>), typeof(FooDecorator), typeof(X), typeof(Y)); | |
var foo = container.Resolve<IFoo<X, Y>>(); | |
StringAssert.Contains("decorated", foo.Message); | |
} | |
public interface IFoo<A, B> | |
{ | |
string Message { get; set; } | |
} | |
[Export] | |
public class X { } | |
[Export] | |
public class Y { } | |
[Export(typeof(IFoo<,>))] | |
class Foo<A, B> : IFoo<A, B> | |
{ | |
public Foo(A a, B b) {} | |
public string Message { get; set; } | |
} | |
// AsFactory says that class has factory method(s) to Export | |
[Export, AsFactory] | |
public class FooDecorator | |
{ | |
// Decorator or kind of instantiation middleware implemented as normal method | |
// Method parameters are injected by container. Lazy, Func, etc are supported | |
// AsDecorator instructs to use result of this method for IFoo<> service, decoratee foo is injected by container. | |
[Export, AsDecorator] | |
public IFoo<A, B> AddMessage<A, B>(IFoo<A, B> foo, Func<A> a, Lazy<B> b) | |
{ | |
foo.Message = $"decorated with {a()} and {b.Value}"; | |
return foo; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment