﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using UserList.Domain;

namespace UserList
{
    public class AutofacConfig
    {
        public static void BuildContainer()
        {

            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterApiControllers(typeof(MvcApplication).Assembly).InstancePerLifetimeScope();
            ServiceRegistration(builder);

            IContainer container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            builder.Register(x => container).As<IContainer>().SingleInstance();
        }

        private static void ServiceRegistration(ContainerBuilder builder)
        {
            builder.RegisterType<DomainContext>()
                .InstancePerLifetimeScope()
                .OnRelease(x => x.Dispose());
        }
    }

}