views:

49

answers:

1

Hi all, i have an interface that defines some methods and i have N classes that implement it. How can i register all the classes found in all the loaded assemblies with autofac?

+1  A: 

You will have to "know about" the assemblies containing the classes, you could perhaps load them yourself with Assembly.Load(..).

From there, it is easy to register the classes:

var assemblies = new[]{....};

builder.RegisterAssemblyTypes(assemblies) 
            .Where(t => typeof(IMyInterface).IsAssignableFrom(t)) 
            .As<IMyInterface>(); 

Update: to get to the registered instances, you can use Autofac builtin support for collections:

public class MyService
{
    private readonly IEnumerable<IMyInterface> _services;
    public MyService(IEnumerable<IMyInterface> services)
    {
        _services = services;
    }

    public void DoStuffWithServices()
    {
        foreach(var svc in _services)
        {
           ...
        }
    }
}
Peter Lillevold
can you write me an exaple of how i could write an extensible debug class that i could register dinamically with autofac? should i use modules? Why?
Stefano
@Stefano - seriously, that question made no sense at all. Is it related to this thread? if not, create a new question and try to explain what your problem is. I cannot, and will not, give you the "codez" without an understandable problem/scenario.
Peter Lillevold
so, it's really simple... i have N classes that implement the same interface and these classes are in different assemblies... so i register all the classes found with your method but i don't know the class name, so how can i call them?
Stefano
@Stefano - see my updated answer.
Peter Lillevold
thank you very much!
Stefano