재우니의 블로그

ASP.NET MVC 5 의 autofac 설정하기

https://github.com/MarlabsInc/SocialGoal/blob/master/source/SocialGoal/App_Start/Bootstrapper.cs

 

global.asax 에서 Application_Start() 함수를 통해 autofac 을 등록한다.

여기서 클래스가 많은 관계로 일일이 기재하기 보다는, 하늘색으로 표기한 부분인 linq 의 where 조건으로 특정 명칭을 가지고 전부 등록하는 부분이 흥미롭다.

using SocialGoal.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SocialGoal
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            System.Data.Entity.Database.SetInitializer(new GoalsSampleData());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
         //   BundleTable.EnableOptimizations = true;
            Bootstrapper.Run();
        }
    }
}

 

using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using System.Reflection;
using SocialGoal.Data.Repository;
using SocialGoal.Data.Infrastructure;
using SocialGoal.Service;
using SocialGoal.Mappings;
using SocialGoal.Web.Core.Authentication;
using Microsoft.AspNet.Identity.EntityFramework;
using SocialGoal.Model.Models;
using SocialGoal.Data.Models;
using Microsoft.AspNet.Identity;

namespace SocialGoal
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();

            //Configure AutoMapper
            AutoMapperConfiguration.Configure();
        }
        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerHttpRequest();
 


            builder.RegisterAssemblyTypes(typeof(FocusRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerHttpRequest();

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

            builder.RegisterAssemblyTypes(typeof(DefaultFormsAuthentication).Assembly)
            .Where(t => t.Name.EndsWith("Authentication"))
            .AsImplementedInterfaces().InstancePerHttpRequest();

            builder.Register(c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>
                       ( new SocialGoalEntities())))
                .As<UserManager<ApplicationUser>>().InstancePerHttpRequest();

            builder.RegisterFilterProvider();
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));            
        }
    }
}

 

등록된 autofac 을 가지고, 객체를 생성하기 위해 new 키워드를 사용하지 않고, 생성자를 통해 원하는 만큼의 객체를 생성한다.

https://github.com/MarlabsInc/SocialGoal/blob/master/source/SocialGoal/Controllers/GoalController.cs

automapper 가 이상하게도.. 아래처럼 initalize 함수가 있어야 하는데,

    Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>());
    //or
    var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());

아래 처럼 생략하고 Mapper.Map 를 곧바로 사용한다.

Goal goal = Mapper.Map<GoalFormModel, Goal>(createGoal);