Support for defered dynamically loaded assemblies?

Jul 9, 2012 at 11:11 PM

Hi,

Is it possible for simple injector to support defered dynamically loaded assemblies?

(The only thing I could think of is to use container.ResolveUnregisteredType but this seems a bit messy, as it would essentially require me to re-create all the dependency injection )

Coordinator
Jul 14, 2012 at 3:18 PM

Loading an implementation (and its assembly) the first its abstraction is used, is not something that is supported out of the box with the Simple Injector. I can't think of any DI container that has support for this out of the box.

You are probably dealing with implementations that are rarely used, and are expensive to load (possibly because they increase the memory use of the application, or because the assemblies are loaded from the internet, such as Silverlight assemblies). The general DI advice in this situation is to use a proxy.

This proxy implements the service type (interface) and it delegates calls to the interface members to the real type. When one of the members is accessed for the first time, the proxy dynamically loads the assembly and pulls the type from that assembly. An implementation could look like this:

// Registration
container.RegisterSingle<IService, DynamicLoadedServiceProxy>();

// Definition
public interface IService
{
    void Execute();
}

// Proxy
public class DynamicLoadedServiceProxy : IService
{
    private static Type implementationType;
    private readonly Container container;

    public DynamicLoadedServiceProxy(Container container)
    {
        this.container = container;
    }

    public void Execute()
    {
        this.GetInstance().Execute();
    }
    
    private IService GetInstance()
    {
        this.Initialize();

        var instance = 
            this.container.GetInstance(this.implementationType);
        
        return (IService)instance;
    }

    private void Initialize()
    {
        if (implementationType == null)
        {
            Assembly assembly = Assembly.LoadFile("plugin.dll");
            Type serviceType = typeof(IService);
        
            implementationType = assembly.GetTypes()
                .Where(t => serviceType.IsAssignableFrom(t))
                .Single();
        }
    }
}
Marked as answer by dot_NET_Junkie on 11/4/2013 at 1:57 AM