依赖注入的惰性解析

问题描述 投票:0回答:4

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

.net dependency-injection unity-container
4个回答
10
投票

还有更好的解决方案 - Unity 2.0 中对 Lazy 和 IEnumerable> 的本机支持。请查看这里


1
投票

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


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<>));

0
投票

在.net core中,删除两个类的构造函数注入,并在使用时通过注入.net IServiceProvider命名空间来实例化其他类。

serviceProvider.GetRequiredService<Service2>().Hi();
© www.soinside.com 2019 - 2024. All rights reserved.