Can any of the existing IoC containers dynamically create lazy proxy classes?

I am learning different DI patterns. And now I'm interested in the lazy realization of life. For example, I want to write a proxy class that hides the factory behind the service interface. Can any of the existing IoC containers (.NET) dynamically create this proxy class at runtime?

interface IService
{
    void Foo();
    void Bar();
}

class ServiceFactoryProxy : IService
{
    private readonly Func<IService> _factory;

    public ServiceFactoryProxy(Func<IService> factory)
    {
        if (factory == null) throw new ArgumentNullException("factory");
        _factory = factory;
    }

    public void Foo()
    {
        _factory().Foo();
    }

    public void Bar()
    {
        _factory().Foo();
    }
}
+3
source share
2 answers

Unity . Func<IService> ( ServiceFactoryProxy) Unity, IService. .


Lazy<T>.

, Unity.

, Unity 3.0 .NET4, , - Unity .


Update2

, . IL-, :

public class MyContract_LazyInstantiationProxy : IMyContract
{
  private readonly Lazy<IMyContract> instance;
  public MyContract_LazyInstantiationProxy(Func<IMyContract> factory)
  {
    Guard.AssertNotNull(factory, "factory");
    this.instance = new Lazy<IMyContract>(factory);
  }
  public IMyContract Instance
  {
    get { return this.instance.Value; }
  }
  public string Foo(Bar bar)
  {
    return this.Instance.Foo(bar);
  }
}

, , .

TecX codeplex. - TecX.Unity.Proxies. , , TecX.Unity.Proxies.Test.

+1

All Articles