Parminder
Parminder

Reputation: 3158

how to avoid autofac reference in all the projects

I am working on asp.net mvc project using autofac as IOC container. I have an interface IDependencyBuilder as given below.

public interface IDependencyBuilder
{
    void Build(ContainerBuilder builder);
}

Now my client projects, if they need to provide some implementation, they implement this interface. For example.

public class SomeDependencyBuilder : IDependencyBuilder
{
  public void Build(ContainerBuilder builder)
    {
        builder.RegisterType<FeedService>().As<IFeedService>();
    }      

}

Now, in my start up procedure. I get all the instances of IDependencyBuilder and call their Build Method

public static void BuildModule(ContainerBuilder builder)
    {
        var type = typeof(IDependencyBuilder);
        var types = AssemblyLocator.GetBinFolderAssemblies().ToList()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p) && !p.IsInterface && !p.IsAbstract);
        foreach (var type in types)
        {
              ((IDependencyBuilder)Activator.CreateInstance(type)).Build(builder);

        }

    }

Everything works perfectly great. Now the problem is I have to add reference to Autofac Library project in all the client projects. Also, If I need to replace autofac with some other IOC container, I would need to change all the codes. So that makes me feel bad. What I want to achieve is return the list of objects (implementation and interfaces) from the client projects and register them in my startup function.

public interface IDependencyBuilderNew
{
   List<SomeObject> GetList();
}

Now the startup function should look like this

public static void BuildModule(ContainerBuilder builder)
{
    var type = typeof(IDependencyBuilderNew);
    var types = AssemblyLocator.GetBinFolderAssemblies().ToList()
        .SelectMany(s => s.GetTypes())
        .Where(p => type.IsAssignableFrom(p) && !p.IsInterface && !p.IsAbstract);
    foreach (var type in types)
    {
          var list  =((IDependencyBuilderNew)Activator.CreateInstance(type)).GetList();
    foreach(var l in list)
    { 
       builder.RegisterType<l.Class>().As<l.InterFace>();
    }
    }


}

How would i implement my SomeObject and what is the best practice for similar situations.

Thanks

Parminder

Upvotes: 1

Views: 566

Answers (1)

Memoizer
Memoizer

Reputation: 2279

  1. Applications should depend on containers. For example, you often change the ORM in your apps? Such architectural decisions must be made in advance.

  2. If so much want to get loose of the concrete IOC container, you can see on Agatha Request/Response Service Layer http://davybrion.github.com/Agatha/

  3. Use Autofac modules instead IDependencyBuilder. It's more flexible. https://code.google.com/p/autofac/wiki/StructuringWithModules

Upvotes: 1

Related Questions