懒惰的依赖注入解决方案

时间:2009-09-11 14:22:09

标签: .net dependency-injection unity-container

我有.net类 我使用unity作为IOC来解决我们的依赖关系。 它尝试在开头加载所有依赖项。 Unity中是否有一种允许在运行时加载依赖的方法(设置)?

3 个答案:

答案 0 :(得分:10)

甚至有更好的解决方案 - 对Lazy< T>的原生支持。和IEnumerable< Lazy< T>>在Unity 2.0中。请查看here

答案 1 :(得分:1)

我在博客上发布了一些代码here,允许将“懒惰”依赖项传递到您的类中。它允许您替换:

class MyClass(IDependency dependency)

class MyClass(ILazy<IDependency> lazyDependency)

这使您可以选择延迟实际创建依赖项,直到需要使用它为止。在需要时致电lazyDependency.Resolve()

以下是ILazy的实现:

public interface ILazy<T>
{
    T Resolve();
    T Resolve(string namedInstance);
}

public class Lazy<T> : ILazy<T>
{
    IUnityContainer container;

    public Lazy(IUnityContainer container)
    {
        this.container = container;
    }

    public T Resolve()
    {
        return container.Resolve<T>();
    }

    public T Resolve(string namedInstance)
    {
        return container.Resolve<T>(namedInstance);
    }
}

您需要在容器中注册才能使用它:

container.RegisterType(typeof(ILazy<>),typeof(Lazy<>));

答案 2 :(得分:0)

我认为Unity应该懒惰地构建实例。你的意思是它正在加载包含其他依赖项的程序集吗?如果是这种情况,您可能需要查看MEF - 它专为模块化应用而设计。