Autofac Dependancy Injection use and configuration

The 'Dependancy Injection' or also called 'Inversion of control containers' is a design pattern that allows us to create more abstract applications and use Interfaces instead of instances of classes. It sounds a little bit scary at the beginning, but in the modern frameworks is actually just a simple configuration. Even it is integrated in some of the most recent frameworks like .NET Core and Angular 4.

You can download a template with the implementation here!

This concept is strongly related to the Object oriented programming and it aims to help us with a couple of things:
Firstly, we no longer depend on specific implementation of a class, and this allows the components to be tested through mocking of dependencies.
Also we can swap dependency implementations in different environments.
Our code becomes loosly coupled
Promotes logical abstraction of components
In old MVC 5 .Net applications the Dependancy Injection is not integrated and you have to install NuGet Package like Autofac or Ninject or something similar.
For our MVC5 templates we use Autofac.
When istall it from the package manager it comes with a AutocafConfig file. Of course it has a default configurations but we have added a few more.


 public static class AutofacConfig
    {
        public static void RegisterAutofac()
        {
            var builder = new ContainerBuilder();

            // Register your MVC controllers.
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();

            // OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule();

            // OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            // Register services
            RegisterServices(builder);

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        private static void RegisterServices(ContainerBuilder builder)
        {
            builder.Register(x => new ApplicationDbContext())
                .As()
                .InstancePerRequest();
            builder.Register(x => new HttpCacheService())
                .As()
                .InstancePerRequest();
            builder.Register(x => new IdentifierProvider())
                .As()
                .InstancePerRequest();

            builder.RegisterType().As().InstancePerRequest();

            builder.RegisterAssemblyTypes(typeof(ICommonService).Assembly)
           .Where(t => t.Name.EndsWith("Service"))
           .AsImplementedInterfaces().InstancePerRequest();

            //this one is in another assembly
            builder.RegisterAssemblyTypes(typeof(ILoggingService).Assembly)
             .Where(t => t.Name.EndsWith("Service"))
             .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterGeneric(typeof(DbRepository<>))
                .As(typeof(IDbRepository<>))
                .InstancePerRequest();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo().PropertiesAutowired();
        }
    }

Most of this code comes by default when we install the Autofac package. All we have to do is to register our dependencies in the RegisterServices method.
This can be done in a couple of ways. Firstly you can register your services one by one. I don't recomend that but sometimes it's the only way. Like in cases when you don't follow some inner convention like the one introduced in our templates.
The convention is simple. Just create a tuple of Interface and class that implements the interface and name them Equally, with the ecxeption of the "I" prefix of the interface, and also make them end up with "Service" suffix.
Doing that you can make an example of a tuple in RegisterServices and tell the container to follow this convention for all similar tuples in the same Assembly. Like in this example.

builder.RegisterAssemblyTypes(typeof(ICommonService).Assembly)
           .Where(t => t.Name.EndsWith("Service"))
           .AsImplementedInterfaces().InstancePerRequest();
Beside that you have an option to set up the type of the instace that you will be provided with. In the following example we get new instance for each new Request.
builder.RegisterType().As().InstancePerRequest();

You have a couple more options like creating a Single Instance (or so called Singleton).
builder.RegisterType().As().SingleInstance();
It depends on what you are tring to achieve.
Moreover you can tell that some class can have autowired properties, which is proven as very useful for base classes, and this is why is set up here.

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo().PropertiesAutowired();
As I mentioned in the new .Net Core you have integrated 'Dependancy Injection' and just have to do the 'RegisterServices' configurations and that is all.
You can download a template of a .NET Core application here!