Balaji
Balaji

Reputation: 2189

Lazy resolution of dependency injection

I have .net classes I am using unity as IOC for resolving our dependencies. It tries to load all the dependencies at the beginning. Is there a way (setting) in Unity which allows to load a dependency at runtime?

Upvotes: 4

Views: 4738

Answers (4)

willingdev
willingdev

Reputation: 9596

in .net core use "Lazy Resolution" : remove both constructor injection of both classes and instantiate other class only when need to use it by injecting the .net IServiceProvider namespace. enter image description here

serviceProvider.GetRequiredService<Service2>().Hi();

Use constructor injection default and only use Lazy Resolution when you have to.

Upvotes: 0

pwlodek
pwlodek

Reputation: 403

There's even better solution - native support for Lazy<T> and IEnumerable<Lazy<T>> in the Unity 2.0. Check it out here.

Upvotes: 10

Mark Heath
Mark Heath

Reputation: 49482

I have blogged some code here to allow passing 'lazy' dependencies into your classes. It allows you to replace:

class MyClass(IDependency dependency)

with

class MyClass(ILazy<IDependency> lazyDependency)

This gives you the option of delaying the actual creation of the dependency until you need to use it. Call lazyDependency.Resolve() when you need it.

Here's the implementation of 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);
    }
}

you will need to register it in your container to be able to use it:

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

Upvotes: 1

TrueWill
TrueWill

Reputation: 25523

Unity should be lazily constructing instances, I believe. Do you mean that it is loading the assemblies containing the other dependencies? If that's the case, you might want to take a look at MEF - it's designed specifically for modular applications.

Upvotes: 1

Related Questions