可以在任何现有的IoC容器中动态创建的懒惰代理类?容器、懒惰、动态、IoC

2023-09-04 00:34:05 作者:白衣无言殇

我研究不同DI模式。 现在我感兴趣的生活懒散时实施。 例如,我想编写一个躲在一个服务的接口工厂代理类。 可以在任何现有的IoC容器(.NET)的创建这样的代理类在运行时动态?

 接口IService
{
    无效美孚();
    无效酒吧();
}

类ServiceFactoryProxy:IService
{
    私人只读Func键< IService> _厂;

    公共ServiceFactoryProxy(Func键< IService>厂)
    {
        如果(厂== NULL)抛出新ArgumentNullException(工厂);
        _factory =工厂;
    }

    公共无效美孚()
    {
        。_factory()的Foo();
    }

    公共无效酒吧()
    {
        。_factory()的Foo();
    }
}
 

解决方案

下面是如何能在城堡来完成:

Spring6 IOC容器架构

http://litemedia.info/lazy-loading-property-with-城堡dynamicproxy2

I study different DI patterns. And now I interested in the lazy life-time implementation. For example, I want to write a proxy class that hides the factory behind a service's interface. Can any of existing IoC containers (.NET) create this kind of proxy class dynamically 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();
    }
}

解决方案

Here is how it can be done in Castle:

http://litemedia.info/lazy-loading-property-with-castle-dynamicproxy2