Search This Blog

Tuesday, November 24, 2015

Autofac Modules C# Tutorial

C# > Patterns > Dependency Injection  > Autofac Modules


Create a project with the following structure:

Project.cs

namespace AutofacModules
{
    public class Project
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Task.cs

namespace AutofacModules
{
    public class Task
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

IProjectRepository.cs

namespace AutofacModules
{
    public interface IProjectRepository
    {
        void Create(Project project);
    }
}

ITaskRepository.cs

namespace AutofacModules
{
    public interface ITaskRepository
    {
        void Create(Task task);
    }
}

ProjectModule.cs

Register a component to be created through reflection.

using Autofac;
namespace AutofacModules
{
    public class ProjectModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ProjectRepository>().As<IProjectRepository>();
            base.Load(builder);
        }
    }
}







TaskModule.cs

using Autofac;
namespace AutofacModules
{
    public class TaskModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<TaskRepository>().As<ITaskRepository>();
            base.Load(builder);
        }
    }
}

RegistrationModule.cs

Add a module to the container.

using Autofac;
namespace AutofacModules
{
    public class RegistrationModule
    {
        public static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule<ProjectModule>();
            builder.RegisterModule<TaskModule>();

            return builder.Build();
        }
    }
}

Example:

            Project project = new Project()
            {
                Id = 1,
                Name = "Project 1"
            };

            Task task = new Task()
            {
                Id = 1,
                Name = "Task 1"
            };

            var container = RegistrationModule.BuildContainer();

//Retrieve a service from the context.

            var projectRepository = container.Resolve<IProjectRepository>();
            var taskRepository = container.Resolve<ITaskRepository>();

            projectRepository.Create(project);
            taskRepository.Create(task);